How much memory does an NSObject take up in OC?

  • The system allocates 16 bytes to the NSObject object (obtained by the malloc_size function)
  • But NSObject is only used internally for 8 bytes of space (available in 64-bit environments via class_getInstanceSize)
  • At 32 bits, a pointer object takes up 4 bytes
#import <Foundation/Foundation.h> #import <objc/runtime.h> #import <malloc/malloc.h> @interface Person : NSObject { @public int _no; int _age; } @end @implementation person@end /* / struct Person_IMPL {struct NSObject_IMPL NSObject_IVARS; int _no; int _age; }; Struct NSObject_IMPL {Class isa; }; Struct Person_IMPL {Class isa; int _no; int _age; } */ int main(int argc, const char * argv[]) { @autoreleasepool { Person *person = [[Person alloc] init]; person->_no = 4; person->_age = 15; NSLog(@"%zd", class_getInstanceSize([Person class])); // 16 NSLog(@"%zd", malloc_size((__bridge const void *)person)); // 16 } return 0; }Copy the code

Why is the size of a pointer 8 on a 64-bit system and 4 on a 32-bit system?

Because a byte is 8 bits: 1byte= 8 bits

  • In 64-bit systems, this bit refers to the data width of the general purpose register in the CPU is 64 bits, that is, an address occupies 64 bits;
  • sosizeof(double *)==sizeof(int *)==sizeof(char *)==64/8==8
  • 32-bit systems, similarly, have an address that occupies 32 bits of binary space;
  • sizeof(double *)==sizeof(int *)==sizeof(char *)==32/8==4
  • LKB = 1024B (Byte)

Why does an instance of a class store only its member variables and not its methods?

  1. Because a class can have many instances;
  2. Member variables can be different for different instances;
  3. But the method is the same;
  4. All methods are stored in instances of class objects