2011-02-06 78 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 

协议是不错的,因为它们提供了多重继承的许多好处,并提供非常少的依赖。