Reputation: 3682
I want to know some features about self
.
self
variable in class method?self.self
allowed in init
method?First:
We have a class ExampleClass
@interface ExampleClass:NSObject
@property (nonatomic,strong) NSString* a;
+(ExampleClass*)createExampleClass;
@end
@implementation ExampleClass
-(id)init{
self = [super init];
if(self){
[self.self init]; #Allowed
[self init]; #Not Allowed ?
}
}
+(ExampleClass*)createExampleClass{
/*do work here*/
NSLog(@"Self: %@ \n Class: %@",self,[self class]);
}
@end
In this example we will see something like this:
Self: ExampleClass
Class: ExampleClass
But why?!
And in init
method [self.self init]
allowed, but not allowed '[self init]'.
Why does this happen?
Upvotes: 1
Views: 185
Reputation: 8546
self.self.self.self.self.self
is also valid :) or [[self self].self self].self.self
Upvotes: -1
Reputation: 85955
self
in class method is the class object itself.
NSObject
has self
method which returns itself.
Self: ExampleClass // Name of the class. Class: ExampleClass // Name of the meta-class object which is same with class object.
If you print pointer address, you will see two objects are different.
Here's nice illustration and description. http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html
Upvotes: 0
Reputation: 81848
self.self
is short for [self self]
which does nothing but return self
.
Upvotes: 0
Reputation: 53551
In a class method, self
is the class. For classes [self class]
simply returns self
, so self
and [self class]
are basically the same thing there.
Calling [self init]
in the init
method doesn't make any sense, it would cause an infinite recursion. However, the compiler error you get is a restriction of ARC, if you'd use self = [self init]
, the error would go away, but it would still make no sense. You might do this in a different initializer method though, to call the designated initializer.
Upvotes: 4