在 Objective-C 中创建一个抽象类 [英] Creating an abstract class in Objective-C

查看:30
本文介绍了在 Objective-C 中创建一个抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm originally a Java programmer who now works with Objective-C. I'd like to create an abstract class, but that doesn't appear to be possible in Objective-C. Is this possible?

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

If not, how close to an abstract class can I get in Objective-C?

推荐答案

通常情况下,Objective-C 类仅按照约定是抽象的——如果作者将一个类记录为抽象类,则不要在没有继承它的情况下使用它.然而,没有编译时强制阻止抽象类的实例化.事实上,没有什么可以阻止用户通过类别(即在运行时)提供抽象方法的实现.您可以通过在抽象类的方法实现中引发异常来强制用户至少覆盖某些方法:

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)];

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

If your method returns a value, it's a bit easier to use

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

那么你就不需要从方法中添加返回语句了.

as then you don't need to add a return statement from the method.

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

If the abstract class is really an interface (i.e. has no concrete method implementations), using an Objective-C protocol is the more appropriate option.

这篇关于在 Objective-C 中创建一个抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆