Creating an abstract class in Objective-C(在 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 中创建一个抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Objective-C 中创建一个抽象类
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01