gaussblurinc
gaussblurinc

Reputation: 3682

Objective-C: Self-variable understanding Issues

I want to know some features about self.

  1. Which context have self variable in class method?
  2. Why 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

Answers (4)

Nicolas Manzini
Nicolas Manzini

Reputation: 8546

self.self.self.self.self.self is also valid :) or [[self self].self self].self.self

Upvotes: -1

eonil
eonil

Reputation: 85955

  1. self in class method is the class object itself.

  2. NSObject has self method which returns itself.

        See here:  https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/self

    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

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81848

self.self is short for [self self] which does nothing but return self.

Upvotes: 0

omz
omz

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

Related Questions