Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 在Objective C中模拟抽象类和抽象方法?_Objective C_Class_Methods_Virtual_Abstract - Fatal编程技术网

Objective c 在Objective C中模拟抽象类和抽象方法?

Objective c 在Objective C中模拟抽象类和抽象方法?,objective-c,class,methods,virtual,abstract,Objective C,Class,Methods,Virtual,Abstract,可能重复: 在Java中,我喜欢使用抽象类来确保一组类具有相同的基本行为,例如: public abstract class A { // this method is seen from outside and will be called by the user final public void doSomething() { // ... here do some logic which is obligatory, e.g. clean up something so that //

可能重复:

在Java中,我喜欢使用抽象类来确保一组类具有相同的基本行为,例如:

public abstract class A
{
// this method is seen from outside and will be called by the user
final public void doSomething()
{
// ... here do some logic which is obligatory, e.g. clean up something so that
// the inheriting classes did not have to bother with it

reallyDoIt();
}
// here the actual work is done
protected abstract void reallyDoIt();

}
现在,如果类B继承自类A,那么它只需实现
reallyDoIt()

如何在目标C中实现这一点?有可能吗?在目标C中是否可行?我的意思是,整个范例在Objective C中似乎不同,例如,据我所知,没有办法禁止重写方法(比如在Java中使用“final”)


谢谢

您需要使用名为“我认为”的方法。

在目标c中不重写方法没有实际限制。您可以使用Dan Lister在回答中建议的协议,但这只适用于强制您的一致性类实现该协议中声明的特定行为

目标c中抽象类的解决方案可以是:

interface MyClass {

}

- (id) init;

- (id) init {
   [NSException raise:@"Invoked abstract method" format:@"Invoked abstract method"]; 
   return nil;
}

通过这种方式,可以防止调用抽象类中的方法(但只能在运行时调用,而不像java这样的语言在编译时可以检测到这种情况)

+1,您可以补充一点,Objective-C是一种更依赖于约定而不是规则执行的语言。作为一名开发人员,您必须遵守这些约定才能使事情顺利进行。协议[几乎]等同于Java中的接口。所以这不是OP真正想要的。我不认为抽象类和协议是完全相同的。考虑:动物*duck=[duck new];协议不是像这样的超级类型。这种构造允许动态地将子类作为参数。如果您有(例如)插件架构,并且希望共享一些代码并希望子类重写其中一些方法,那么抽象类非常有用。阅读更多这里看到这个帖子谢谢,这实际上是我想做的。我只是希望能有某种方法在编译时告诉实现继承类的程序员一个方法丢失了,而不是在运行时子类崩溃?