Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Todd Baker
Todd Baker
17,207 Points

Clarification on self in Objective-C

I am struggling with the practice of calling self in Objective-C. If I am calling the object that was defined using @implementation THDanceNode, then [self runAction:repeatAction] is essentially equal to [THDanceNode runAction:repeatAction]. Am I thinking of this correctly? Thanks!

2 Answers

Stone Preston
Stone Preston
42,016 Points

self refers to an instance of the class in instance methods, or the class itself in class methods.

if I had an instance method and inside that method I had something like

    //calls runSomeMethod on whatever instance of the class is calling it. self in this case refers to an instance of the class
    [self runSomeMethod]

if I had a class method (take initialize for instance)

+ (void)initialize {
    //self refers to the current class. so if this was in THDanceNode then self = THDanceNode
    if (self == [THDanceNode class]) { 
        // ...
    }
}

so back to your original question:

then [self runAction:repeatAction] is essentially equal to [THDanceNode runAction:repeatAction].

the above is true if self was used inside a class method. if its not inside a class method then that is not correct. self refers to an instance of the class, or the actual object of the class itself thats calling the method when not in a class method. since spriteKit actions are run on objects, its more likely that the above is used inside an instance method and that self refers to an instance of THDanceNode, not the class THDanceNode, but I cant be sure without seeing some more code.

Todd Baker
Todd Baker
17,207 Points

That makes a lot of sense. I need to do a bit more practice to see different situations so that the differences become clearer.

Sebastian Cain
Sebastian Cain
2,565 Points

yes. "self" refers to a method run directly on the class.

Stone Preston
Stone Preston
42,016 Points

that isnt exactly correct. self does not refer to a method, it refers to either an instance of the class or the class itself