MNY
MNY

Reputation: 1536

Is the `id` type used often writing Objective C programs?

I'm reading the book "Programming in Objective C" and he explained not too much on the id type and didn't give much exercise on it, so I'm wondering how often do you use id and if programmers most of the time avoid it? (since he explained some issues with it)

I'm sure it's used, would be great if you can mention some cases it is the only solution..like real life programming cases from some kind of app development.

Upvotes: 4

Views: 131

Answers (3)

nneonneo
nneonneo

Reputation: 179392

id is the universal type in Objective C. It can represent a * of any Objective-C type, such as NSString *, NSArray *, etc. The neat thing about Objective-C is that you can send messages to id, and if the object on the other end understands the message, it will get processed as usual without the sender having to know the real type.

It's commonly used when defining anything generic. For example, NSArray is an array of ids; it's up to the programmer to put a specific kind of object in the container (e.g. NSNumber, NSString, etc.). It's used in a lot of other places in Objective-C (such as when defining IBActions for the interface builder, when defining init methods, etc.).

Upvotes: 4

vikingosegundo
vikingosegundo

Reputation: 52227

id is the generic object type in Objective-C. It can hold any object.

one real world example: parsing json you wont know, if the root element is a array or a dictionary. But id would take them both.

I use it a lot, but often in conjunction with a protocol definition: id<NetworkPrinterProtocol>. This means that it should be an object of any kind but it does fulfill the NetworkPrinterProtocol. Often used for defining delegates.

see WP: Objective-C — Dynamic Typing

Upvotes: 2

rmaddy
rmaddy

Reputation: 318794

The id is kind of like a catch-all data type. It is used to hold values of any type.

Common uses are for the return type of init... methods. It's used by the collection classes since they can hold any object. See the various getter methods return values and the various methods for adding/setting objects in the mutable version of collection classes.

It's also used in combination with protocols when you need a reference to an object that can be any class but must adhere to a protocol. Examples include many of the delegate properties such as the UITableView delegate.

Upvotes: 2

Related Questions