开发者

What does this syntax mean in Objective-C?

Consider the following:

- (id)initWithTitle:(NSString *)newTitle
     boxOfficeGross:(NSNumber *)newBoxOfficeGross
            summary:(NSString *)newSummary;

What does this mean? I've guessed that it returns id, and takes three params, but what does each part of the syntax mean? I come from a Ruby/JS background and am finding this syntax a little hard to 开发者_开发知识库grasp.


It's an instance method (ie, not a static or "class" method) called initWithTitle:boxOfficeGross:summary: that returns an object of type id (generic object). It takes three parameters: a String object, a Number object, and another String object.

You invoke it like this:

NSNumber * gross = [NSNumber numberWithInteger:1878025999]
Movie * avatar = [[Movie alloc] initWithTitle:@"Avatar"
                               boxOfficeGross:gross
                                      summary:@"Pocahontas in the 22nd century"];
//or you can do it all on one line, like so:
Movie * avatar = [[Movie alloc] initWithTitle:@"Avatar" boxOfficeGross:gross summary:@"Pocahontas in the 22nd century"];


  • - means that the method is an instance method, not a class method.
  • (id) means it returns an id, as you surmised.
  • initWithTitle:, boxOfficeGross:, and summary: are part of the method name. In Objective-C, each parameter generally has an associated method name part. The entire name of the method is initWithTitle:boxOfficeGross:summary.
  • (NSString *), etc., denote the type of the parameter.
  • newTitle, etc., is the name of the parameter.


The - designates an instance method, whereas if it were a + it would be a class method.

The (id) is what the method will return, which is simply a reference to an object.

The rest of the line shows the parameters. When calling the function, you write out the part of each parameter before the :, such as [class initWithTitle:@"my title"];

The reason why there are two names for each parameter is because the method itself will refer to the variable by whatever is after the :, so the title will be newTitle.

This was confusing to me at first, but there are advantages to it.

Also, the parts of each parameter inside parenthesis are the object type of the parameter. (NSString *) is a pointer to a NSString. If you were to pass something that wasn't an NSObject, such as an NSIntger, you would not need the *. You'd simply do: -(id)initWithInteger:(NSIntger)newInteger;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜