Is it okay for multiple objects to retain the same object in Objective-C/Cocoa?
Posted
by Andrew Arrow
on Stack Overflow
See other posts from Stack Overflow
or by Andrew Arrow
Published on 2010-04-26T17:29:56Z
Indexed on
2010/04/26
17:33 UTC
Read the original article
Hit count: 218
Say I have a tableview class that lists 100 Foo objects. It has:
@property (nonatomic, retain) NSMutableArray* fooList;
and I fill it up with Foos like:
self.fooList = [NSMutableArray array]; while (something) { Foo* foo = [[Foo alloc] init]; [fooList addObject:foo]; [foo release]; }
First question: because the NSMutableArray is marked as retain, that means all the objects inside it are retained too? Am I correctly adding the foo and releasing the local copy after it's been added to the array? Or am I missing a retain call?
Then if the user selects one specific row in the table and I want to display a detail Foo view I call:
FooView* localView = [[FooView alloc] initWithFoo:[self.fooList objectAtIndex:indexPath.row]]; [self.navigationController pushViewController:localView animated:YES]; [localView release];
Now the FooView class has:
@property (nonatomic, retain) Foo* theFoo;
so now BOTH the array is holding on to that Foo as well as the FooView. But that seems okay right? When the user hits the back button dealloc will be called on FooView and [theFoo release] will be called. Then another back button is hit and dealloc is called on the tableview class and [fooList release] is called.
You might argue that the FooView class should have:
@property (nonatomic, assign) Foo* theFoo;
vs. retain. But sometimes the FooView class is called with a Foo that's not also in an array. So I wanted to make sure it was okay to have two objects holding on to the same other object.
© Stack Overflow or respective owner