我最初是一名Java程序员,现在使用Objective-C。我想创建一个抽象类,但这在Objective-C中似乎不可能。这可能吗?
如果不是,在Objective-C中,我能有多接近抽象类?
我最初是一名Java程序员,现在使用Objective-C。我想创建一个抽象类,但这在Objective-C中似乎不可能。这可能吗?
如果不是,在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的必要性
其他回答
问题的答案散落在已经给出答案的评论中。所以,我只是在这里总结和简化。
Option1:协议
如果你想创建一个没有实现的抽象类,请使用“协议”。继承协议的类必须实现协议中的方法。
@protocol ProtocolName
// list of methods and properties
@end
选项2:模板方法模式
如果你想创建一个带有部分实现的抽象类,如“Template Method Pattern”,那么这就是解决方案。 Objective-C -模板方法模式?
创建抽象类的简单示例
// Declare a protocol
@protocol AbcProtocol <NSObject>
-(void)fnOne;
-(void)fnTwo;
@optional
-(void)fnThree;
@end
// Abstract class
@interface AbstractAbc : NSObject<AbcProtocol>
@end
@implementation AbstractAbc
-(id)init{
self = [super init];
if (self) {
}
return self;
}
-(void)fnOne{
// Code
}
-(void)fnTwo{
// Code
}
@end
// Implementation class
@interface ImpAbc : AbstractAbc
@end
@implementation ImpAbc
-(id)init{
self = [super init];
if (self) {
}
return self;
}
// You may override it
-(void)fnOne{
// Code
}
// You may override it
-(void)fnTwo{
// Code
}
-(void)fnThree{
// Code
}
@end
你不能创建一个委托吗?
委托就像一个抽象基类,你说需要定义什么函数,但实际上你不定义它们。
然后,每当你实现委托(即抽象类)时,编译器就会警告你需要为哪些可选函数和强制函数定义行为。
对我来说,这听起来像一个抽象基类。
你可以使用@Yar提出的方法(做了一些修改):
#define mustOverride() @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"%s must be overridden in a subclass/category", __PRETTY_FUNCTION__] userInfo:nil]
#define setMustOverride() NSLog(@"%@ - method not implemented", NSStringFromClass([self class])); mustOverride()
在这里你会得到这样的消息:
<Date> ProjectName[7921:1967092] <Class where method not implemented> - method not implemented
<Date> ProjectName[7921:1967092] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[<Base class (if inherited or same if not> <Method name>] must be overridden in a subclass/category'
或断言:
NSAssert(![self respondsToSelector:@selector(<MethodName>)], @"Not implemented");
在这种情况下,你会得到:
<Date> ProjectName[7926:1967491] *** Assertion failure in -[<Class Name> <Method name>], /Users/kirill/Documents/Projects/root/<ProjectName> Services/Classes/ViewControllers/YourClass:53
您也可以使用协议和其他解决方案-但这是最简单的解决方案之一。
(更多相关的建议)
我想有一种方法让程序员知道“不要从子调用”,并完全覆盖(在我的情况下,仍然提供了一些默认功能,代表父时,未扩展):
typedef void override_void;
typedef id override_id;
@implementation myBaseClass
// some limited default behavior (undesired by subclasses)
- (override_void) doSomething;
- (override_id) makeSomeObject;
// some internally required default behavior
- (void) doesSomethingImportant;
@end
这样做的好处是程序员会看到声明中的“override”,并且知道他们不应该调用[super ..]。
当然,必须为此定义单独的返回类型是很难看的,但它可以作为一个足够好的视觉提示,并且您可以很容易地在子类定义中不使用“overrides”部分。
当然,当扩展是可选的时,类仍然可以有默认实现。但是,就像其他答案所说的那样,在适当的时候实现一个运行时异常,比如对于抽象(虚拟)类。
如果有像这样的内置编译器提示就好了,甚至提示什么时候最好预/后调用super的实现,而不是不得不挖掘注释/文档或…假设。