A Objective-C object memory structure is what?

problem

A Objective-C object memory structure is what?

answer

This is an old problem, perhaps a lot of people are ready for, in fact, if not every company examined the case, this question can look at the candidate level of interest to the underlying principle behind the iOS. Really interested in programming for students, will be how much of this has some curious, and then search the Internet and learn the information in this regard.

The following is a simple answer to this question:

If the instance of the class as a C language structure (struct), which contains a first isa pointer, while the other members of the class variables are sequentially arranged in the structure. The order shown below:


In order to verify this statement, we create a new project in Xcode, run the following code in main.m in:

#import <UIKit/UIKit.h>

@interface Father : NSObject {    
   int _father; }
@end@implementation Father

@end

@interface Child : Father {    
int _child; }
@end

@implementation Child

@end

int main(int argc, char * argv[]) {  Child * child = [[Child alloc] init];  
 @autoreleasepool {      
      // ...  } }

We will next breakpoint in @autoreleasepoolplace, and then enter in Console p *child, you can see the following output Xcode, which is consistent with our previous statement.

(lldb) p *child
(Child) $0 = {
  (Father) Father = {
    (NSObject) NSObject = {
      (Class) isa = Child
    }
    (int) _father = 0
  }
  (int) _child = 0
}

Because the objects are arranged in the memory can be regarded as a structure, the size of the structure does not change dynamically. It is not possible to dynamically increase the object member variables at runtime.

Note: You need to explain, through objc_setAssociatedObjectand objc_getAssociatedObjectcan disguise the object to increase the member variable method, but the implementation mechanism is not the same, so not really change the memory structure of the object.

Guess you like

Origin www.cnblogs.com/pioneerMax/p/6420432.html