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];
}
- In the .h file do we need to declare the title and sub when we add the property. is it not enough to add the @property (retain) NSString *title; line.
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.
1-
You don’t need to declare the iVar in the header. You might also use
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:
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