isa pointer in objective-c

前端 未结 4 1869
感动是毒
感动是毒 2021-02-02 14:20

From this reference:

When a new object is created, memory for it is allocated, and its instance variables are initialized. First among the object’s vari

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-02 14:49

    At runtime, when a message is sent to an object, that object goes to the class that created it and says: "I was sent this message. Run the code of the matching method." This is different than most compile language, where the method to be executed is determined at compile time.


    HOW DOES AN OBJECT KNOW WHICH CLASS CREATED IT?

    It uses its isa pointer. Every object has an instance variable called isa. When an object is created, the class sets the isa instance variable of the return object to point back at that class. It is called the isa pointer because an object "is a" instance of that class. Although you probably will never explicitly use the isa pointer, it existence gives Objective-C gets much of its power.


    An object only responds to a message if its class (pointed to by its isa pointer) implements the associated method. Because this happens at runtime, XCode cannot always figure out at compile time (when the application is built) whether an object will respond to a message. XCode will give you an error if it thinks you are sending message to an object that will not respond, but if it is not sure, it will let the application build.


    If, for some reason (and there are many possibilities), you end up sending a message to an object that does not respond, your application will thrown an exception. So the isa pointer is the reason for runtime error . Let's check detail and example here: IOS - Objective-C - Exceptions And Unrecognized Selectors

提交回复
热议问题