Setting a object with "Assign" property to nil
If I am having a variable defined with "Assign" property then is it ok to setting them to nil in dealloc method?
@property (nonatomic, assign) id test;
- (void)dealloc {
self.te开发者_StackOverflow社区st = nil;
}
It's better to release the ivar directly. If a subclass overrides the setter methods of a property, your object might leak because your setter is not called. Consider:
@interface ClassA
@property (readwrite, retain) id anObject;
@end
@interface ClassB : ClassA
@end
@implementation ClassA
@synthesize anObject;
- (void)dealloc {
self.anObject = nil;
[super dealloc];
}
@end
@implementation ClassB
- (void)setAnObject: (id)anObject {
// do nothing!
}
@end
Instances of ClassB will leak anObject
!
Depends how you do it, if you do it via the property setter (not recommended), then yes.
If you do direct assignment, then no, because the retained object will leak.
So this is fine:
- (void) dealloc {
self.test = nil;
[super dealloc];
}
But this is a no-go:
- (void) dealloc {
test = nil;
[super dealloc];
}
My advice is to just send the release
message to all of your retained ivars in -dealloc
, this will work nicely because if test
happens to be nil
, then nothing will happen.
Trust me. Send release
directly in -dealloc
. That is all.
- (void) dealloc {
[test release];
[super dealloc];
}
精彩评论