1

When a new object is created and initialized why do we use id? Can't we use (NSObject*)?

RK-
  • 12,099
  • 23
  • 89
  • 155
  • Yes, you can. Here is the [article](http://unixjunkie.blogspot.com/2008/03/id-vs-nsobject-vs-id.html) that explains all this things... – demon9733 Apr 23 '12 at 15:19

2 Answers2

6

Not every object in Objective C is NSObject. There are other root classes (for example, NSProxy), that are not derived from NSObject.

id means absolutely any object. Everything is Objective C that can receive messages (including Class) can be passed as id without type warnings.

NSObject* is only useful on objects that are actually derived from NSObject. If you pass something that is not derived from it, type checker will complain.

hamstergene
  • 24,039
  • 5
  • 57
  • 72
  • 4
    Almost; one big reason why `id` is used is because it doesn't require a cast to a more specific type whereas `NSObject*` does. – bbum Apr 23 '12 at 17:57
1

Because NSObject is a distinct Objective C class. It's the base class for most everything (* but not everything, +1 to HamsterGene), but it's still a class.

And if you assigned a new object (of any type that descends from NSObject) to it, you'd lose the inheritence & properties of whatever subclassed type you had created were.

id is roughly equivalent to void * in it's behavior where you can assign any Objective C object to an id, like how you can assign any random chunk of memory (with no care for it's contents or type) to a void *.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215