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.
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 id
s; 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 IBAction
s for the interface builder, when defining init
methods, etc.).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With