IOS interview question – how many bytes does an nsobject object occupy?

Time:2022-1-11

How many bytes does an nsobject object occupy?

  • stayObjective-CIn, we can get one through some methodsNSObjectHow many bytes does the object occupy

  • Code acquisitionNSObjectThe byte size of the member variable of the instance object

    • Gets the byte size occupied by the member variable of an nsobject instance objectruntimeAPI,class_getInstanceSizeTo get, get8
    /** 
     * Returns the size of instances of a class.
     * 
     * @param cls A class object.
     * 
     * @return The size in bytes of instances of the class \e cls, or \c 0 if \e cls is \c Nil.
     */
    OBJC_EXPORT size_t
    class_getInstanceSize(Class _Nullable cls) 
        OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
    
    • You can alsomallocLibrary API,malloc_sizeTo get, get16
    extern size_t malloc_size(const void *ptr);
    /* Returns size of given ptr */
    
  • The following is the actual combat code

#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <malloc/malloc.h>

// NSObject Implementation
struct NSObject_IMPL {
    Class isa; //  8 bytes
};
//Pointer
// typedef struct objc_class *Class;

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSObject *obj = [[NSObject alloc] init];
        //16 bytes
        
        //Get the size occupied by the member variable of the nsobject instance object > > 8
        NSLog(@"%zd", class_getInstanceSize([NSObject class]));
        
        //Get the memory size pointed to by the obj pointer > > 16
        NSLog(@"%zd", malloc_size((__bridge const void *)obj));
        
        //What platform code
        //The code supported by different platforms must be different
        // Windows、mac、iOS
        //Simulator (i386), 32bit (armv7), 64bit (arm64)
        //You can generate C + + files through command line tools
        // xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m -o main-arm64.cpp
        //Then drag the successfully compiled cpp file into the project. Note that copy items if needed is not checked
        //Then delete main-arm64.0 from build phases CPP compilation options (select the file, click the minus sign or press the delete key)
        //In this way, if the file does not participate in compilation, there will be no error
    }
    return 0;
}
  • Through the generated compiled code, we knowNSObjectObjects are essentiallyC++ofstructural morphologyThe structure is about this long
// NSObject Implementation
struct NSObject_IMPL {
    Class isa; //  8 bytes
};

Find out through objc source code

  • Now the core implementation source code of some of Apple’s underlying libraries has been opened. We can download it from the official website

    • addresshttps://opensource.apple.com/tarballs/objc4/
    • Select the version number to view the latest download
  • Check the source code, once foundif size < 16 size = 16, less than 16 will be directly set to 16

inline size_t instanceSize(size_t extraBytes) const {
        if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
            return cache.fastInstanceSize(extraBytes);
        }

        size_t size = alignedInstanceSize() + extraBytes;
        // CF requires all objects be at least 16 bytes.
        if (size < 16) size = 16;
        return size;
    }
  • CoreFoundationHard rules in the framework, memory alignment, less than16Will be set to16

Look at the memory structure with Xcode

  • Break point

image.png
  • stayXcodeMenu bar selectedDebug -> Debug Workflow -> View Memory

image.png
  • The memory structure is shown in the figure below

image.png
  • You can also use the commonly used lldb instructions to view

image.png
  • See the following figure for printing

image.png

summary

  • OneNSObjectHow many bytes does the object occupy

answer

  1. System assigned16Bytes toNSObjectObject (viamalloc_sizeFunction get)
  2. howeverNSObjectObject is only used internally8A space of bytes (in 64bit environment, it can be accessed throughclass_getInstanceSizeFunction), which is actuallyisa

Extend to objects with inheritance structure

  • StudentInherited fromNSObject
  • The code structure is as follows
struct Student_IMPL {
    Class isa;
    int _no;
    int _age;
};


@interface Student : NSObject
{
    @public
    int _no;
    int _age;
}
@end

@implementation Student

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Student *stu = [[Student alloc] init];
        stu->_no = 4;
        stu->_age = 5;
        
        // 16
        NSLog(@"%zd", class_getInstanceSize([Student class]));
        // 16
        NSLog(@"%zd", malloc_size((__bridge const void *)stu));
        
        struct Student_IMPL *stuImpl = (__bridge struct Student_IMPL *)stu;
        // no is 4, age is 5
        NSLog(@"no is %d, age is %d", stuImpl->_no, stuImpl->_age);
    }
    return 0;
}
  • Approximate memory structure diagram

image.png

Extended to structures with multiple inheritance

  • The following figure shows the inheritance structure
@interface Person: NSObject
{
    int _age;
}
@end

@implementation Person

@end

@interface Student : Person
{
    int _no;
}
@end

@implementation Student

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person = [[Person alloc] init];
        // 16
        NSLog(@"person --- %zd", class_getInstanceSize([Student class]));
        // 16
        NSLog(@"person --- %zd", malloc_size((__bridge const void *)person));
        
        Student *stu = [[Student alloc] init];
        // 16
        NSLog(@"stu --- %zd", class_getInstanceSize([Student class]));
        // 16
        NSLog(@"stu --- %zd", malloc_size((__bridge const void *)stu));
    }
    return 0;
}
  • The structure is as follows

image.png
  • OnePersonObject, oneStudentHow much memory does the object occupy?
  • The answer is, it’s all 16
  • Approximate memory structure diagram

image.png
  • Due to memory alignment, the size of the structure must be the maximum member size(16)Multiple of

Objective-CByte size occupied by different data types

  • Can passsizeofTo get the byte size occupied by different data types
  • sizeofIn fact, it is not a function, but just an operation operator, which is determined at compile time
type 32-bit machine 64 bit machine
BOOL 1 1
bool 1 1
int 4 4
short 2 2
long 4 8
long long 8 8
NSInteger 4 8
float 4 4
double 8 8
CGFloat 4 8
char 1 1
Pointer address 4 8