Is the 'isa' variable in objective-C equal to 'instanceof' in Java

匿名 (未验证) 提交于 2019-12-03 02:47:02

问题:

Simple question: is it fair to say that the 'isa' instance variable in Objective-C provides the same functionality as the 'instanceof' operator in Java?

回答1:

These are different concepts.

One is a member of a struct, while another is an operator.

To mimic a strict interpretation of the instanceof operator in Java, you can do pointer comparison on the isa member:

if(obj->isa == [SomeClass class]) {   //obj is an instance of SomeClass }

But it is recommended that you use the NSObject protocol's -isMemberOfClass: method to accomplish this instead:

if([obj isMemberOfClass:[SomeClass class]]) {   //obj is an instance of SomeClass }

If you are interested in knowing if the specified class is an instance of, or is a subclass of another class, you should use the NSObject protocol's -isKindOfClass: method.



回答2:

From the Objective-C programming guide:

id is defined as pointer to an object data structure:

typedef struct objc_object {   Class isa; } *id;

Every object thus has an isa variable that tells it of what class it is an instance. Since the Class type is itself defined as a pointer:

typedef struct objc_class *Class;

the isa variable is frequently referred to as the “isa pointer.”



回答3:

No. instanceof is more like the isKindOfClass: method in Objective-C because it also evaluates to true for subclasses while the isa pointer only points to a single class.



回答4:

In 64-bit implementations of the Objective-C runtime, isa became 64-bits - like all other pointers.

Apple is using a clever trick to speed things up: they are relying on the fact that all 64-bits aren't used for the address, so they are using some of the bits to store things like retain count. This way they don't need to go modify the retain count for an object in a separate table with all the performance implications that that entails.

What this means is that direct comparison of the isa pointer does not work at all. This is true for OS X and now iOS 7 on the 64-bit A7 (iPhone 5s).

Treat isa as an implementation detail. Do not access it directly. Use -isMemberOfClass: which will do the proper thing (which in 64-bit OSes now involves masking off part of isa).

More info: http://www.sealiesoftware.com/blog/archive/2013/09/24/objc_explain_Non-pointer_isa.html



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!