I am a newer to objective c. I have read the memory management document on apple's "Memory Management Rules". But I am still not very clear about how to manage reference for a property.
What's the default implementation of set/get access methods for a p开发者_高级运维roperty declared with "retain" annotation?
This is my assuming, please give some comments. Thanks.
@interface SubClass : NSObject {
NSString * _name;
}
... ...
@property (nonatomic, retain) NSString * name;
... ...
@end
-(NSString *) setName {
return _name;
}
-(void) setName: (NSString *) pName{
// the correct version of default set method for retain
if( _name != pName ) {
[_name release];
_name = [pName retain];
}
}
So the dealloc method, is this ok?
- (void)dealloc {
self.name = nil; // or [_name release], _name = nil;
}
As Matteo Alessani says, you can simply synthesize the property to get the default implementations.
For reference, this is what's generated (I got this from reading Objective-C Declared Properties and piecing information together):
- (NSString *)name {
return _name;
}
- (void)setName:(NSString *)aName {
if (_name != aName) {
[_name release];
_name = [aName retain];
}
}
You can use synthesize in your implementation file:
@implementation SubClass
@synthesize name = _name;
@end
Automatically you get the default getter and setter.
As Matteo said you can synthesize accessor methods automatically.
But speaking about implementation details:
yes getter method may look like (but note the correct name):
-(NSString *) name { return _name; }
or to handle the case when you use name value and object that holds it gets deallocated:
-(NSString *) name { return [[_name retain] autorelease]; }
setter method:
-(void) setName: (NSString *) pName{ NSString *temp = [pName retain]; [_name release]; _name = temp; }
dealloc. Your implementation is ok, but as calling properties may cause some side effects relying that all fields in your object are valid (which may not be so in dealloc method) it may be better to release ivar directly.
Your setter example is wrong as you don't need to handle nil case (actually in your code you can never set name value to nil), but you need to handle the case when property is set to the same object.
精彩评论