[英]Obj-c: Custom Object handling
我正在創建自己的自定義對象,並且想知道是否需要保留我的屬性或使用其他內容(例如復制)(這是做什么的?)?
@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
另外,在我的.m文件中,我是否還需要合成和發布?
《 Objective-C編程語言》中的“ 聲明的屬性 ”一章介紹了copy
功能以及有關訪問器的綜合的信息。
我個人的喜好:
@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
在典型情況下,您的.m將具有以下行:
@synthesize name;
...
這告訴編譯器自動發出getter / setter方法。 您也可以自己編寫/覆蓋這些內容。 因此,當某人執行fooAsset.name = x時,您的對象將保留其對'x'的引用。 您需要做的另一件事是使用dealloc方法釋放對成員的引用:
- (void)dealloc {
[name release];
....
[super dealloc];
}
請注意,如果從不分配“名稱”,則仍然適用; nil會默默地吃掉“釋放”消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.