2011-02-06 51 views
0

比方說,我創建一個類,MasterClass,然後創建另外4個類,每個子類都有MasterClass,我希望每個子類都實現一個返回對象的特定方法。該大師班本身更與普通的實用方法,等殼類的。什麼是使用,而不是正確的格式:Obj-c noob有關無子類型返回類型的子類化問題?

// implemented by subclass 
-(MyObject*)doSomething{} 

其OBV拋出一個編譯器錯誤?

THX

+0

只需在該方法中返回`nil` ... – 2011-02-06 05:29:36

回答

0

你所描述的面向對象的語言被稱爲abstract class。 Objectove-C不支持抽象類。但是,您可以在超類中聲明該方法並使其實現引發異常。這將迫使你的子類重載它並實現所需的行爲。從StackOverflow看到這篇文章。

0

我不知道我理解你的問題,但這裏有一個鏡頭:你要這樣定義你的接口:

@interface Subclass1 : MasterClass 

然後實現你的方法如常。 聲明:

-(MyObject*)doSomething; 

實現:

-(MyObject*)doSomething{ 

//Stuff... 

} 
0

這裏就是我在明確的子結構的情況下使用:

@class MyObject; 

@interface MONBase : NSObject 

/* required override */ 
-(MyObject *)doSomething; 

/* ... */ 

@end 

@implementation MONBase 

/* ... */ 

-(MyObject*)doSomething 
{ 
    assert(0 && "this override is required"); 
    return nil; 
} 

@end 

然而 ...協議通常通常在這些以及類似的情況下更加有用。下面展示了一種實現這一點的方法。它實現了一個協議,從共享基地繼承 - 從OP的使用情況中得到使用:

@class MyObject; 

@protocol MONProtocol 

/* required overrides: */ 
@required 
- (MyObject *)doSomething; 

/* optional overrides: */ 
@optional 

@end 

/* base, with shared implementation */ 
@interface MONBase : NSObject 
@end 

@implementation MONBase 

- (MyObject *)doSomething 
{ 
    /* 
    as long as the sig matches, you won't need to declare it in the interface -- that may be a good thing. 
    you may prefer *not* to implement this, if you favor a runtime exception 
    */ 
    assert(0 && "this MONProtocol override is required"); 
    return nil; 
} 

@end 

/* subclass of MONBase which extends by implementing MONProtocol */ 
@interface MONSub : MONBase <MONProtocol> 
{ 
    MyObject* theIvar; /* << simplest case implementation */ 
} 

@end 

@implementation MONBase 

/* ... */ 

- (MyObject *)doSomething 
{ 
    return [[theIvar retain] autorelease]; 
} 

@end 

協議是不錯的,因爲它們提供了多重繼承的許多好處,並提供非常少的依賴。