What does the [SomeClass self] syntax do?
Asked Answered
E

1

5

I am currently studying the sample code provided by Apple for Sketch and I stumbled upon some syntax that I haven't seen before. It's in SKTGraphicView.m in the function moveSelectedGraphicsWithEvent:

NSRect selBounds = [[SKTGraphic self] boundsOfGraphics:selGraphics];

I have never seen the [SomeClass self] syntax before. In this case self is a subclass of NSView and boundsOfGraphics: is a class method for SKTGraphic which is a subclass of NSObject.

Epitasis answered 21/3, 2014 at 17:36 Comment(2)
possible duplicate of Using self in class methodHistrionic
This question is different than that one. This is asking about a call to the -[NSObject self] method, not the use of the self "keyword" as it is normally used.Noisette
P
8

The self method is defined in the NSObject protocol, so every object be it an instance of a class or a class object (of type Class) supports the method. It simply returns the object it is called on, i.e. something like:

- (id) self { return self; }

So self on an instance returns the instance, and on a class object returns the class object.

The following therefore holds: [x self] == x is YES for all instance and class objects x

And your line is equivalent to:

NSRect selBounds = [SKTGraphic boundsOfGraphics:selGraphics];

So that is what it does. As to why Apple wrote it this way, that's a different question...

Patellate answered 21/3, 2014 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.