Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between id<protocol> and NSObject<protocol>

In Objective-C, id<protocol> or NSObject<protocol> are frequently used for delegate declaration.

What are the main differences between id and NSObject? When do you want to use one versus the other?

like image 443
Boon Avatar asked Dec 13 '13 13:12

Boon


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 NSObjectprotocol?

The group of methods that are fundamental to all Objective-C objects.

How do I create an NSObject in Objective-C?

Creating a Custom Class Go ahead an choose “Objective-C class” and hit Next. For the class name, enter “Person.” Make it a subclass of NSObject. NSObject is the base class for all objects in Apple's developer environment. It provides basic properties and functions for memory management and allocation.


1 Answers

id<protocol> obj is the declaration for any object that conforms to the specified protocol. You can send any message from the given protocol to the object (or from the protocols that <protocol> inherits from).

NSObject<protocol> *obj is the declaration for any object that

  • conforms to the given protocol, and
  • is derived from NSObject.

That means that in the second case, you can send any methods from the NSObject class to the object, for example

id y = [obj copy];

which would give a compiler error in the first case.

The second declaration also implies that obj conforms to the NSObject protocol. But this makes no difference if <protocol> is derived from the NSObject protocol:

@protocol protocol <NSObject>
like image 97
Martin R Avatar answered Nov 02 '22 23:11

Martin R