1

I have a question about a certain type of method syntax.

For example I know what this does ..

NSString *theString = [[NSString alloc]init...blablabla];

The alloc is performed on the class (NSString in this case) and the init is performed on the instance of the class..

If we have

[variable method];

I know how that functions too.. the method is performed on "variable"

if I have

variable = [instance method];

the "method" method is performed on instance and stored in variable..

But where I get lost is at something that looks like this ..

[[CCDirector sharedDirector]something:parameter];

I'm not sure what action is being performed where..

Jeff Wolski
  • 6,332
  • 6
  • 37
  • 69
Heartbound07
  • 219
  • 1
  • 2
  • 8
  • It's important to understand that what you're talking about is not procedural. The method is not being performed on the variable or class. You're sending a message to to the variable or class, and in this specific case, the message you're sending happens to be the name of a method. – Jeff Wolski Dec 29 '11 at 16:33

4 Answers4

5

[CCDirector sharedDirector] is getting the singleton instance of the director. Then you are calling the something method with parameter. It would be similar to doing this

CCDirector* director = [CCDirector sharedDirector];
[director something:parameter];
hspain
  • 17,528
  • 5
  • 19
  • 31
0

The brackets mean the same everywhere. The message expression [object arg0:value arg1:value ...] sends the message @selector(arg0:arg1:...) to object (which could itself be a message expression). The message handler can return an object, so the value of a message expression can itself be the recipient of another message. Nesting these expressions is the same as nesting function calls:

something(CCDirector_sharedDirector(), parameter);

CCDirector_sharedDirector() doesn't actually exist; it's just used for comparison.

Note that in:

[[NSString alloc] init...]

It's not so much that init is sent to an NSString instance (it isn't, as [NSString alloc] actually returns an NSCFString), it's that init is sent to the result of [NSString alloc].

If you find nested messages hard to read, you can break them into multiple lines or use temporary variables.

[[CCDirector sharedDirector]
    something:parameter];
Community
  • 1
  • 1
outis
  • 75,655
  • 22
  • 151
  • 221
0

[CCDirector sharedDirector] is a method on CCDirector, and returns some object. Much like [NSString alloc]. The rest of the line calls a method on the object that's returned.

cHao
  • 84,970
  • 20
  • 145
  • 172
0

As @hspain pointed out, its a convention used to denote a singleton instance. The actual alloc/init occurs, and is only occured once, within sharedDirector.

Here is more information on the singleton pattern in objective-c.

Jeremy
  • 8,902
  • 2
  • 36
  • 44