Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

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.

like image 708
MNY Avatar asked Feb 17 '23 12:02

MNY


2 Answers

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.).

like image 168
nneonneo Avatar answered May 11 '23 01:05

nneonneo


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

like image 45
vikingosegundo Avatar answered May 11 '23 01:05

vikingosegundo