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];
}
Yes.
UIView *mySubview;'defines a local variable,mySubview, which is a pointer to — a reference to — an instance of theUIViewclass. 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-releaseto the instance of ofUIViewincluded innotification.That
releaseis balancing theretainimplied by thealloc. Which isn’t the right pattern at all. You should do something like:Oh, by “class property”, I’m assuming you mean “instance variable”?