views:

37

answers:

1

Please look at the code below and suggest 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];
    }
+2  A: 

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"?

bbum
Perfect, that's what I needed to clarify. So in the second function, the last two lines will reduce the reference count to 0 and the original instance will be freed from memory, is that right?
Anna
Maybe it reduces it to 0, maybe not. Don't worry about that -- all you need to worry about is making sure all of your retains (and implied retains) are balanced by releases. What the object(s) or frameworks might do internally is an implementation detail beyond your control. I.e. retain count is merely a delta, never an absolute. In this case, the code is correct because everything is in balance.
bbum
Ah, I see. Thank you.
Anna