我有 2 个关于如何在 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 potential leak at 'return 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
现在,这是我的问题:
- 是否可以使用解决方案 1 并消除“潜在泄漏”?
- 解决方案 2 是常见解决方案吗?
谢谢大家!
-- 托尼
最佳答案
根据要求,我将我的评论转载为答案:
[[NSMutableArray alloc] array]
应该给你一个编译器警告,它肯定会崩溃。你需要 [[NSMutableArray alloc] init]
。
关于iphone - 如何编写正确的只读属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4930031/