iOS> " ID"与NSObject相比 [英] iOS > "id" vs. NSObject

查看:114
本文介绍了iOS> " ID"与NSObject相比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对象相关的对象 id 类型的多态方式之间是否存在差异 NSObject *

Is there a difference between relating to an Object in a 'Polymorphic' way with the type id than as NSObject *?

以什么方式:

NSString* aString = @"Hello";
id anObj = aString;

不同于:

NSString* aString = @"Hello";
NSObject* anObj = aString;


推荐答案

id 是Objective-C中使用的特殊关键字,意思是某种对象。它不包含 isa 指针( isa ,赋予对象访问其类的权限,并通过该类访问它继承的所有类,因此您将丢失有关该对象的编译时信息。

id is a special keyword used in Objective-C to mean "some kind of object." It does not contain isa pointer(isa, gives the object access to its class and, through the class, to all the classes it inherits from), So you lose compile-time information about the object.

NSString* aString = @"Hello";
id anObj = aString;  

NSObject 包含 isa 指针。

NSString* aString = @"Hello";
NSObject* anObj = aString;

来自 Objective-C是动态语言

考虑以下代码:

id someObject = @"Hello, World!";
[someObject removeAllObjects];

在这种情况下,someObject将指向 NSString 实例,但除了它是某种对象之外,编译器对该实例一无所知。 removeAllObjects 消息由一些Cocoa或Cocoa Touch对象定义(例如 NSMutableArray ),因此编译器不会抱怨,即使此代码在运行时会生成异常,因为NSString对象无法响应 removeAllObjects

In this case, someObject will point to an NSString instance, but the compiler knows nothing about that instance beyond the fact that it’s some kind of object. The removeAllObjects message is defined by some Cocoa or Cocoa Touch objects (such as NSMutableArray) so the compiler doesn’t complain, even though this code would generate an exception at runtime because an NSString object can’t respond to removeAllObjects.

重写代码以使用静态类型:

Rewriting the code to use a static type:

NSString *someObject = @"Hello, World!";
[someObject removeAllObjects];

表示编译器现在会生成错误,因为 removeAllObjects 未在它知道的任何公共 NSString 界面中声明。

means that the compiler will now generate an error because removeAllObjects is not declared in any public NSString interface that it knows about.

这篇关于iOS> " ID"与NSObject相比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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