[英]Obj-c: Custom Object handling
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? 另外,在我的.m文件中,我是否还需要合成和发布?
《 Objective-C编程语言》中的“ 声明的属性 ”一章介绍了copy
功能以及有关访问器的综合的信息。
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
For typical cases your .m will have lines like this: 在典型情况下,您的.m将具有以下行:
@synthesize name;
...
That tells the compiler to automatically emit the getter/setter methods. 这告诉编译器自动发出getter / setter方法。 You can also write/override these yourself.
您也可以自己编写/覆盖这些内容。 So, when someone does a fooAsset.name = x, your object will retain its own reference to 'x'.
因此,当某人执行fooAsset.name = x时,您的对象将保留其对'x'的引用。 The other thing you need is a dealloc method to release the references to your members:
您需要做的另一件事是使用dealloc方法释放对成员的引用:
- (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.
nil会默默地吃掉“释放”消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.