What's the difference between declaring a variable “id” and “NSObject *”?

后端 未结 4 658
野性不改
野性不改 2020-12-01 04:40

In Objective-C, what\'s the difference between declaring a variable id versus declaring it NSObject *?

4条回答
  •  醉话见心
    2020-12-01 05:09

    id means "an object", NSObject * means "an instance of NSObject or one of its subclasses". There are objects in Objective-C which are not NSObjects (the ones you'll meet in Cocoa at the moment are NSProxy, Protocol and Class). If some code expects an object of a particular class, declaring that helps the compiler check that you're using it properly. If you really can take "any object" - for instance you are declaring a delegate and will test all method sends with respondsToSelector: calls - you can use an id.

    Another way to declare an object variable is like "id ", which means "any object which implements the NSObject protocol.

提交回复
热议问题