This is the second day of my participation in Gwen Challenge

In our last post, we explored the story behind alloc and concluded that alloc is all about allocating memory, and allocating memory involves three key operations:

  • How much memory to allocate
  • allocated
  • After allocation, the marker block is associated with the class

So today we’re going to dig deeper and explore more details.

This article focuses on how much memory alloc allocates.

We create an object allocated memory, is certainly to be able to install this object, it must have something to do with the class structure, within a class contains attributes and methods, method of members on the one hand, will be stored in class object isa pointer to other place we call it a metaclass (metaclass), on the other hand, members of the method are immutable, So member methods should be free of memory.

So that leaves the properties, and let’s say that the size of memory depends on the properties of the object. Let’s define a class in OC:

@interface YTPerson : NSObject
{
    NSString  *name;
    NSInteger age;
    double    weight;
}
@end

@implementation YTPerson

@end
Copy the code

Since the research to the bottom, we have to mention that we know in C language is no class, object such data structure, similar to C language only structure, we use the following command to convert the OC code file into C language, see how in C language this class is represented.

xcrun -sdk iphoneos  clang -arch arm64 -rewrite-objc main.m -o main.c
Copy the code

Sure enough, we can find similar code in main.c:

struct YTPerson_IMPL {
	struct NSObject_IMPL NSObject_IVARS;
	NSString *name;
	NSInteger age;
	double weight;
};
Copy the code

The YTPerson_IMPL structure corresponds exactly to the YTPerson property defined in OC.