In many places you can see how self and [self class] are called, so are they different?
1 First what is self, which is a pointer to the first address of the instance variable (as in C + +) can access the object's resources.
2 [Self class] first look at class it returns a pointer to a meta class, so you can access the static function of the current class through [self class]
Why does [self class] have access to the class pointer and can look at the structure of the NSObject:
@interface NSObject <nsobject> {
Class Isa objc_isa_availability;
}
Any class is inherited from NSObject so in memory Isa is the first address, and self points to the address of ISA.
Look at how the class is called in runtime, first to get the ISA variable of the NSObject class, and to return the pointer to the Meta class through ISA, so that class is the class pointer that returns the current class.
-(Class)class {
return object_getclass(self);
}
Class Object_getclass (ID obj)
{
if (obj) return obj->Getisa();
Else return Nil;
}
3 then [self class] In addition to access to static functions, is there any other use of variables? Look at the following example
@interface engine:nsobject<nscopying>
@end
@implementation Engine
-(ID) Copywithzone: (nszone *) zone{
return [[Self class]allocwithzone: Zone]init];
}
We need to send the message to a class, not an instance variable. So which class should I send it to? Intuition tells us that we should be the engine, like this: [Engine allocwithzone: zone];
But this line of code only applies to the engine class, not for it. If a copy message is sent to its subclass Slant6, the last time the engine object is created, the copy of the engine class is used instead of the copy of the Slant6 class.
So to use [self class] He can send a message to the class that the object that is accepting the copy message belongs to. If self is an Slvant6 object, it is sent to Slvant6.
On the difference between self and self class usage