2013-05-08 101 views

回答

6

嚴格來說,Objective-C中沒有「抽象類」或「抽象屬性」,例如,請參閱此線程Creating an abstract class in Objective-C以獲得良好的概述。

你的做法是不是最佳的,因爲它需要的父類實現foosetFoo:,這與「抽象」的想法。

更好的解決方法是在超類中定義一個「動態屬性」:

@interface SuperClass : NSObject 
@property (strong, nonatomic) Foo *foo; 
@end 

@implementation SuperClass 
@dynamic foo; 
@end 

,並明確合成它的子類:

@interface SubClass : SuperClass 
@end 

@implementation SubClass 
@synthesize foo = _foo; 
@end 

現在你可以在子類對象上訪問foo ,但是在超類對象上它會導致運行時異常。

對於延遲初始化,可以使用通常的模式,而沒有任何「超招數」:

- (Foo *) foo 
{ 
    if(!_foo) _foo = [[Foo alloc] init]; 
    return _foo; 
} 

一種替代方法(在上面螺紋也提到)是使用「協議」,而不是 共同的超類:

@protocol HasFoo <NSObject> 
- (Foo *)foo; 
@end 

@interface MyClass : NSObject<HasFoo> 
@property(strong, nonatomic) Foo *foo; 
@end 

@implementation SubClass 
- (Foo *) foo 
{ 
    if(!_foo) _foo = [[Foo alloc] init]; 
    return _foo; 
} 
@end 
+0

謝謝馬丁。我仍然在學習在Obj-C中思考。這很有意義。 – izk 2013-05-08 18:47:19

相關問題