iOS开发--OC对象模型你必须知道的几条规则

来源:互联网 发布:windows编程视频下载 编辑:程序博客网 时间:2024/05/16 18:35

1.每一个对象都有一个isa的指针,指向该对象的类。


2.每一个类描述了一系列它的实例的特点,包括成员变量的列表、成员函数的列表等。


3.每一个对象都可以接收消息,而对象能够接收的消息列表保存在它所对应的类中。


4.每个类也有一个名为isa的指针,每个类也可以接收消息。


5.类也是一个对象,所以它也必须是另一个类的实例,这个类就是元类。元类保存了类方法列表。当一个类方法被调用时,元类会首先查找它本身是否有该类方法的实现,如果没有,则该类会向它的父类查找该方法,这样可以一直找到继承链的头。


6.元类也是一个对象,所有元类的isa指针都会指向一个根元类。根元类本身的isa指针指向自己,这样就可以形成一个闭环。


7.所有子类的元类都会继承父类的元类,换而言之,类对象和元类对象有着同样的继承关系。


8.nsobject的元类继承自nsobject类,所以nsobject类是所有类的根,nsobject的元类指向自己。


9.对象在内存中的排布可以看成一个结构体,该结构体的大小并不能动态变化,所以无法在运行时动态地给对象增加成员变量。


10.对象的方法都保存在类的可变区域,我们可以看到方法的定义列表是一个名methodlists的指针的指针,通过修改该指针的值,就可以动态地为某一个类增加成员方法,这也是category实现的原理。


注:选取自唐巧iOS开发进阶一书。


补充

下面是官方文档的描述:

The key to messaging lies in the structures that the compiler builds for each class and object. Every class structure includes these two essential elements:

A pointer to the superclass.

A class dispatch table. This table has entries that associate method selectors with the class-specific addresses of the methods they identify. The selector for thesetOrigin::method is associated with the address of (the procedure that implements)setOrigin::, the selector for thedisplaymethod is associated withdisplay’s address, and so on.


When a new object is created, memory for it is allocated, and its instance variables are initialized. First among the object’s variables is a pointer to its class structure. This pointer, calledisa, gives the object access to its class and, through the class, to all the classes it inherits from.


When a message is sent to an object, the messaging function follows the object’sisapointer to the class structure where it looks up the method selector in the dispatch table. If it can’t find the selector there, objc_msgSendfollows the pointer to the superclass and tries to find the selector in its dispatch table. Successive failures causeobjc_msgSendto climb the class hierarchy until it reaches theNSObjectclass. Once it locates the selector, the function calls the method entered in the table and passes it the receiving object’s data structure. This is the way that method implementations are chosen at runtime—or, in the jargon of object-oriented programming, that methods are dynamically bound to messages.


To speed the messaging process, the runtime system caches the selectors and addresses of methods as they are used. There’s a separate cache for each class, and it can contain selectors for inherited methods as well as for methods defined in the class. Before searching the dispatch tables, the messaging routine first checks the cache of the receiving object’s class (on the theory that a method that was used once may likely be used again). If the method selector is in the cache, messaging is only slightly slower than a function call. Once a program has been running long enough to “warm up” its caches, almost all the messages it sends find a cached method. Caches grow dynamically to accommodate new messages as the program runs.



0 0