开发者

How to release objects stored in an array?

Please look at the code below and 开发者_如何学Csuggest the best approach. I can't quite tell whether the code is correct. When adding objects to arrays, do they get a retain count? In the second function, am I releasing the local variable "mySubview" or the original object?

    // this is a class property
    myArray = [[NSMutableArray alloc] init];    


    - (void)createSubview
    {
        UIView *mySubview = [[UIView alloc] init];
        [self addSubview:mySubview];


        [myArray addObject:mySubview];

    }

    -(void)eventHandler:(NSNotification *) notification
    {
        UIView *mySubview = [notification object];

        [myArray removeObjectIdenticalTo:mySubview];

        [mySubview removeFromSuperview];
        [mySubview release];
    }


When adding objects to arrays, do they get a retain count?

Yes.

In the second function, am I releasing the local variable "mySubview" or the original object?

UIView *mySubview;' defines a local variable, mySubview, which is a pointer to -- a reference to -- an instance of the UIView class. There is no such thing as a "local object" or "stack object" in Objective-C (save for blocks, but that is beyond the scope of this question).

So, no, when you call [mySubview release] you are sending -release to the instance of of UIView included in notification.

That release is balancing the retain implied by the alloc. Which isn't the right pattern at all. You should do something like:

- (void)createSubview
{
    UIView *mySubview = [[UIView alloc] init];
    [self addSubview:mySubview];
    [myArray addObject:mySubview];
    [mySubview release];
}

-(void)eventHandler:(NSNotification *) notification
{
    UIView *mySubview = [notification object];
    [myArray removeObjectIdenticalTo:mySubview];
    [mySubview removeFromSuperview];
}

Oh, by "class property", I'm assuming you mean "instance variable"?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜