Reputation: 2848
I have few questions to ask about the following class
#import <Cocoa/Cocoa.h>
@interface SomeObject {
NSString *title;
}
@property (retain) NSString *title;
@end
implementation SomeObject
@synthesize title;
-(id)init {
if (self=[super init])
{
self.title=[NSString stringWithFormat:@"allyouneed"];
}
return self;
}
-(void)testMethod{
self.title=[[NSString alloc] init] ;
}
-(void)dealloc {
self.title=nil;
[super dealloc];
}
2.Do i need to autorelease both assignment to title in the init and testMethod. if So why?
Can some one explain these things to me.
Upvotes: 0
Views: 114
Reputation: 71
Be aware it is not considered a good practice to use accessor methods in initializer methods and dealloc method. Do check out this answer: Why shouldn't I use Objective C 2.0 accessors in init/dealloc?
Also in Apple's memory management guide: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html
Upvotes: 0
Reputation: 523
1- You don't need to declare the iVar in the header. You might also use
@synthesize myVar = _myVar;
if you want to go for a different iVar name
2- Declaring a property "retain" means that every time you assign the property with a new object, it automatically releases the previous object and retain the new one.
Therefore, if you use a convenience method like stringwithFormat, the property will retain that object for you.
If you want to use alloc-init, for me the best way to do is:
NSString *str = [NSString alloc] init];
self.title = str;
[str release];
Besides, it is right to assign nil to the property in the dealloc because the property will release the object it has, and it calls retain on nil which doesn't do anything
Upvotes: 2
Reputation: 12405
you don't need to add as it is done automatically (Since Xcode 4 I guess).
in init- you don't as it already returns an autoreleased
object..
where as in testMethod
you need to since you are allocating it..
you always have to release any object which you create using alloc
, copy
or new
.... AMEN.. :)
Upvotes: 0
Reputation: 3408
1.No need to declare title in .h, declaring property is enough.
2.when you are using self.title in init, you do not have to autorelease it.But when you initialize it in testMethod, you need to autorelease it because you have declare the property as retain.And do not forget to release title in dealloc.
Upvotes: 0