What does this syntax mean in Objective-C?

Consider the following:

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

What does it mean? I guessed that it returns id and takes three parameters, but what does each part of the syntax mean? I come from the background of Ruby / JS and find this syntax a little difficult to understand.

+4
source share
3 answers

This is an instance method (that is, not a static or β€œcool” method) called initWithTitle:boxOfficeGross:summary: which returns an object of type id (shared object). It takes three parameters: a String object, a Number object, and another String object.

You call 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"]; 
+5
source
  • - means that the method is an instance method, not a class method.
  • (id) means that it returns id , you guessed it.
  • initWithTitle: boxOfficeGross: and summary: are part of the method name. In Objective-C, each parameter usually has a part of the method name associated with it. The full name of the initWithTitle:boxOfficeGross:summary .
  • (NSString *) , etc., indicate the type of parameter.
  • newTitle etc. is the name of the parameter.
+4
source

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

(id) is that the method will return, which is just a reference to the object.

The rest of the line shows the options. When you call the function, you write a part of each parameter before : for example [class initWithTitle:@"my title"];

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

At first it was confusing, but there are advantages.

In addition, the parts of each parameter in brackets are a type of parameter object. (NSString *) is a pointer to an NSString . If you need to pass something that was not an NSObject , like NSIntger , you won’t need * . You simply do: -(id)initWithInteger:(NSIntger)newInteger;

0
source

Source: https://habr.com/ru/post/1299670/


All Articles