Is it necessary temporary variable when allocating ivar used only in that class?
If ivar is used by other classes, I use @property (noatomic, retain) and @synthesize. And I add it to t开发者_如何学Gohe view like this. label is ivar.
UILabel *aLabel = [UILabel alloc] initWithFrame:frame];
self.label = aLabel;
[aLabel release];
[self.view addSubview:label];
But if it is not used by other classes, I do not use @property and @synthesize. And I add it to the view like this.
label = [UILabel alloc] initWithFrame:frame];
[self.view addSubview:label];
Am I right?
label = [UILabel alloc] initWithFrame:frame];
[self.view addSubview:label];
That's possibly correct but dangerous. It's fine if the previous value of label was nil. If label had a different value before, then that's a memory leak, because you didn't release the object previously pointed to by label, but that object afterwards has one less reference, and possibly no references left.
Properties are useful for things like that even if they are not used by other classes. However they are not required.
Yes, but the last line of the first example should be
[self.view addSubview:self.label];
yes, don't forget the release in dealloc. properties are primarily necessary to allow access to values from outside your class. The are essentially methods, a getter and a setter that pass through the value. Retaining and copying properties additionally retain the value or make a copy of it. So often they are used to simplify your code if you need to retain something, because then you can simply set self.property = value and don't need to explicitly retain it and release the previous value.
You should use @property
in both cases. The difference is that you should move the @property
definition into a private extension if you don't want it public. For example, consider the following pubName
and privName
properties.
// MYObject.h -- Public Interface
@interface MYObject : NSObject
@property (nonatomic, readwrite, retain) NSString *pubName;
@end
// MYObject.m
@interface MYObject () // Private Interface
@property (nonatomic, readwrite, retain) NSString *privName;
@end
@implementation MYObject
@synthesize pubName=pubName_;
@synthesize privName=privName_;
- (void)dealloc {
[pubName_ release];
[privName_ release];
}
You should then always use accessors for all properties, whether they are public or private (except in init and dealloc). Doing this consistently is the best defense against memory management mistakes (leading to leaks and crashes).
精彩评论