Objective-C (iPhone) ivars and memory management
iphone, objective-c
Solution
Using `@synthesize` will actually only create a setter and a getter method. The code that is auto generated for you is guaranteed to use proper memory management, so that you do not need to worry.
MGTwitterEngines use of `return [[ivar retain] autorelease`] is actually the correct way to do it. Lets have two examples.
Assume a getter is defined as this:
-(Foo)foo {
return foo;
}
And then we execute this code:
- `bar = [[bar alloc] init];` // bar has aretain count of 1.
- `foo = bar.foo;` // foo har a retain count of 1 (owned by bar).
- `[bar release];` // Bar and all it's ivars are released imidiatetly!
- `[foo doSomething];` // This will crash since the previous line released foo.
If we instead change the getter to this:
-(Foo)foo {
return [[foo retain] autorelease];
}
- `bar = [[bar alloc] init];` // bar has a retain count of 1
- `foo = bar.foo;` // foo has a retain count of 2 (one owned by bar, 1 owned by autorelease pool).
- `[bar release];` // Bar and all it's ivars are released imidiatetly!
- `[foo doSomething];` // Will not crash since foo is still alive and owned by autorelease pool.
Hope this explains why you should always return properly autoreleased objects from all your getters. It is important that any return value can survive the deallocation of it's parent, since no class ca guarantee what a client will do with it's values once it is exposed to the wild.
Problem
I am subclassing NSURLConnection, and used MGTwitterEngine as a base to help me get started. That may be irrelevant. However, I noticed in their code they don't use `@property` or `@synthesize` for their ivars. They have wrapped the ivars in accessor methods which look like this: ``` - (NSString *)identifier { return [[_identifier retain] autorelease]; } ``` My question is two part. First, what effect does `retain` followed by `autorelease` have? It seems to me it would cancel itself, or worse yet leak. Second, if I were to change the header file to have: ``` @property (nonatomic, retain, readonly) NSString* _identifier; ``` And used `@synthesize indentifier = _identifier`, wouldn't this do the same thing as the accessor method without having to write it? Maybe it is just two different ways to do the same thing. But I wanted to ensure I have the correct understanding. Thanks.