关于如何在Objective-C 2.0+中生成正确的只读属性,我有两个问题。
这是我最初的方法,让我们称之为解决方案1:
@interface ClassA{
@private
NSMutableArray *a_;
}
// NOTE: no retain
@property (nonatomic, readonly) NSMutableArray *a;
@end
///////////////////////////////////////
@implementation ClassA
@synthesize a = a_;
- (NSMutableArray *)a{
if(nil == a_){
a_ = [[NSMutableArray alloc] array];
}
// Potential leak warning on the following line.
return a_;
}
- (void)dealloc{
// I released the object here, I think this should be safe.
[a_ release];
[super dealloc];
@end
当我编译和分析它时,系统会报告这样的警告:“返回a_时可能发生泄漏”。
然后我再次阅读了Objective-C的文档,发现了另一种方法如下。让我们称之为解决方案2。
@interface ClassB{
@private
NSMutableArray *a_;
}
// NOTE: make it retain+readonly
@property (nonatomic, readonly, retain) NSMutableArray *a;
@end
///////////////////////////////////////
// Add a private category
@interface ClassB ()
// reset the property to readwrite
@property (nonatomic, readwrite, retain) NSMutableArray *a;
@end
//////
@implementation ClassB
@synthesize a = a_;
- (id)init{
if(self = [super init]){
// NOTE: set the value as we use property normally.
self.a = [NSMutableArray array];
}
return self;
}
- (void)dealloc{
self.a = nil;
[super dealloc];
@end
现在,我的问题如下:
- Is it possible to use solution 1 and get rid of potential leak ?
- Does solution 2 the common solution?
谢谢你们!
--托尼