Reputation: 42139
I am creating my own custom object, and I am wondering if I need to retain my properties or use something else such as copy (which does what?)?
@interface Asset : NSObject {
NSString *name;
NSNumber *assetId;
NSNumber *linkId;
NSNumber *parentId;
}
@property (nonatomic, retain) NSString *name; // should I use retain here or something else?
@property (nonatomic, retain) NSNumber *assetId;
@property (nonatomic, retain) NSNumber *linkId;
@property (nonatomic, retain) NSNumber *parentId;
@end
Also, in my .m, do I also need synthesize as well as release?
Upvotes: 1
Views: 210
Reputation: 28059
My personal preference:
@interface Asset : NSObject {
// no need to declare them here the @synthesize in the .m will sort all that out
}
// use copy for NSString as it is free for NSString instances and protects against NSMutableString instances being passed in...thanks to @bbum for this
@property (nonatomic, copy) NSString *name;
// no need for copy as NSNumber is immutable
@property (nonatomic,retain) NSNumber *assetId;
@property (nonatomic,retain) NSNumber linkId;
@property (nonatomic,retain) NSNumber parentId;
@end
Upvotes: 1
Reputation: 5286
For typical cases your .m will have lines like this:
@synthesize name;
...
That tells the compiler to automatically emit the getter/setter methods. You can also write/override these yourself. So, when someone does a fooAsset.name = x, your object will retain its own reference to 'x'. The other thing you need is a dealloc method to release the references to your members:
- (void)dealloc {
[name release];
....
[super dealloc];
}
Note that it'll still be appropriate if 'name' is never assigned; nil will silently eat the 'release' message.
Upvotes: 1
Reputation: 21882
The chapter on Declared Properties in The Objective-C Programming Language explains what copy
does and about synthesizing accessors.
Upvotes: 4