What does isa mean in objective-c?

后端 未结 2 870
暖寄归人
暖寄归人 2020-12-04 08:51

I would like to know the meaning of the below written lines with an example. I\'m unable to understand what the lines actually mean. The lines are from google\'s objective-c

2条回答
  •  一个人的身影
    2020-12-04 09:18

    Under the hood, Objective-C objects are basically C structs. Each one contains a field called isa, which is a pointer to the class that the object is an instance of (that's how the object and Objective-C runtime knows what kind of object it is).

    Regarding the initialization of variables: in Objective-C, instance variables are automatically initialized to 0 (for C types like int) or nil (for Objective-C objects). Apple's guidelines say that initializing your ivars to those values in your init methods is redundant, so don't do it. For example, say you had a class like this:

    @interface MyClass : NSObject
    {
        int myInt;
        double myDouble;
        MyOtherClass *myObj;
    }
    @end
    

    Writing your init method this way would be redundant, since those ivars will be initialized to 0 or nil anyway:

    @implementation MyClass
    
    - (id)init
    {
        if ((self = [super init])) {
            myInt = 0;
            myDouble = 0.0;
            myObj = nil;
        }
        return self;
    }
    
    @end
    

    You can do this instead:

    @implementation MyClass
    
    - (id)init
    {
        return [super init];
    }
    
    @end
    

    Of course, if you want the ivars to be initialized to values other than 0 or nil, you should still initialize them:

    @implementation MyClass
    
    - (id)init
    {
        if ((self = [super init])) {
            myInit = 10;
            myDouble = 100.0;
            myObj = [[MyOtherClass alloc] init];
        }
        return self;
    }
    
    @end
    

提交回复
热议问题