我最初是一名Java程序员,现在使用Objective-C。我想创建一个抽象类,但这在Objective-C中似乎不可能。这可能吗?

如果不是,在Objective-C中,我能有多接近抽象类?


当前回答

从Omni组邮件列表:

Objective-C没有像Java那样的抽象编译器结构 这一次。

因此,您所要做的就是将抽象类定义为任何其他正常类 并为抽象方法实现方法存根 空或报告不支持选择器。例如……

- (id)someMethod:(SomeObject*)blah
{
     [self doesNotRecognizeSelector:_cmd];
     return nil;
}

我还执行以下操作来防止抽象的初始化 通过默认初始化式初始化。

- (id)init
{
     [self doesNotRecognizeSelector:_cmd];
     [self release];
     return nil;
}

其他回答

只是重复了上面@Barry Wark的回答(并更新到iOS 4.3),并把这个留给我自己参考:

#define mustOverride() @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"%s must be overridden in a subclass/category", __PRETTY_FUNCTION__] userInfo:nil]
#define methodNotImplemented() mustOverride()

在你的方法中你可以使用这个

- (void) someMethod {
     mustOverride(); // or methodNotImplemented(), same thing
}

注意:不确定是否使宏看起来像一个C函数是一个好主意,但我会保持它直到学校相反。我认为使用NSInvalidArgumentException(而不是NSInternalInconsistencyException)更正确,因为这是运行时系统在响应doesNotRecognizeSelector被调用时抛出的(参见NSObject文档)。

Cocoa不提供任何所谓抽象的东西。我们可以创建一个只在运行时检查的类抽象,而在编译时不检查。

Typically, Objective-C class are abstract by convention only—if the author documents a class as abstract, just don't use it without subclassing it. There is no compile-time enforcement that prevents instantiation of an abstract class, however. In fact, there is nothing to stop a user from providing implementations of abstract methods via a category (i.e. at runtime). You can force a user to at least override certain methods by raising an exception in those methods implementation in your abstract class:

[NSException raise:NSInternalInconsistencyException 
            format:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)];

如果您的方法返回一个值,那么使用起来会更容易一些

@throw [NSException exceptionWithName:NSInternalInconsistencyException
                               reason:[NSString stringWithFormat:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)]
                             userInfo:nil];

这样就不需要从方法中添加return语句了。

如果抽象类实际上是一个接口(即没有具体的方法实现),使用Objective-C协议是更合适的选择。

我通常只在我想要抽象的类中禁用init方法:

- (instancetype)__unavailable init; // This is an abstract class.

这将在编译时在该类上调用init时生成一个错误。然后我用类方法来处理其他事情。

Objective-C没有内置的方法来声明抽象类。

另一种替代方法

只要在抽象类和断言或异常中检查类,无论你喜欢什么。

@implementation Orange
- (instancetype)init
{
    self = [super init];
    NSAssert([self class] != [Orange class], @"This is an abstract class");
    if (self) {
    }
    return self;
}
@end

这消除了重写init的必要性