Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS > "id" vs. NSObject [duplicate]

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

In what way is:

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

different than:

NSString* aString = @"Hello";
NSObject* anObj = aString;
like image 385
Ohad Regev Avatar asked Oct 28 '13 12:10

Ohad Regev


People also ask

Is ID an NSObject?

id is a language keyword but the NSObject is the base class in objective c. For id, you dont need to typecast the object. But for NSObject, you have to typecast it into NSObject.

What is NSObject in iOS?

The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.1+ tvOS 9.0+ watchOS 2.0+

What is equivalent of ID in Swift?

In Swift 3, the id type in Objective-C now maps to the Any type in Swift, which describes a value of any type, whether a class, enum, struct, or any other Swift type.


1 Answers

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;  

enter image description here

NSObject contain isa pointer.

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

enter image description here

From Objective-C Is a Dynamic Language

Consider the following code:

id someObject = @"Hello, World!";
[someObject 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];

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

like image 56
Parag Bafna Avatar answered Nov 04 '22 12:11

Parag Bafna