我有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_’潛在的泄漏」 。
然後我再次閱讀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]數組]`應該給你一個編譯器警告,它肯定會崩潰。你想`[[NSMutableArray alloc] init]`。 – 2011-02-08 05:54:07
你在`NSMutableArray a_;`裏忘了`*`這裏` – EmptyStack 2011-02-08 06:47:54
@Simon,謝謝,我用手輸入了它,沒有用編譯器編譯。我修復了它。 – 2011-02-09 10:01:28