为什么要子类NSObject? [英] Why subclass NSObject?

查看:121
本文介绍了为什么要子类NSObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C中NSObject的用途/用途是什么?我看到扩展NSObject的类如下:

What is the purpose/use of NSObject in Objective-C? I see classes that extend NSObject like this:

@interface Fraction : NSObject 

在C ++或Java中,我们不使用任何变量,如NSObject,即使我们在Objective-C和Java中都有预处理程序指令和import语句。

In C++ or Java, we don't use any variables like NSObject even though we have preprocessor directives and import statements in both Objective-C and Java.

为什么类在Objective-C中明确地从NSObject继承?不从NSObject声明继承的后果是什么?

Why do classes explicitly inherit from NSObject in Objective-C? What are the consequences of not declaring inheritance from NSObject?

推荐答案

我们使用NSObject明确说明给定类继承的内容。我不确定C ++,但是在Java中有类似的东西 - Object类。唯一的区别是Java不要求显式类从Object继承 - 该语言假定任何没有指定父类的类都来自Object。 Objective-C是不同的,因为它允许您定义不同的根类 - 您允许创建一个不从NSObject继承的类。

We use NSObject to explicitly state what a given class inherits from. I'm not sure about C++, but in Java there's something similar - the Object class. The only difference is that Java doesn't require that classes explicitly descend from Object - the language assumes anything that doesn't have a specified parent class descends from Object. Objective-C is different because it allows you to define different root classes - you are allowed to make a class that doesn't inherit from NSObject.

这种不同的根类的一个例子是 NSProxy

An example of such a different root class is NSProxy.

看一下 GNUstep NSObject源,它显示了方法如何与objective-c运行时交互通过C函数。

Have a look at the GNUstep NSObject source, it shows how the methods interact with the objective-c runtime through C functions.

+ (id) allocWithZone:(NSZone*)z
{
  return NSAllocateObject(self, 0, z);
}

- (void) dealloc
{
  NSDeallocateObject (self);
}

+ (BOOL) isSubclassOfClass: (Class)aClass
{
  return GSObjCIsKindOf(self, aClass);
}

这篇关于为什么要子类NSObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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