Объективные методы C + (id) - PullRequest
0 голосов
/ 26 июня 2011

Я в некоторой степени новичок в Objective-C, поэтому я хотел бы спросить, как мне создавать методы, которые возвращают сами объекты.Позвольте мне показать пример:

В NSArray вы можете сделать [NSArray arrayWithObjects:bla,bla,nil];

Как я могу создать такой метод для своего класса?

1 Ответ

4 голосов
/ 26 июня 2011

С этим методом происходят две основные вещи:

  1. Это метод класса (т. Е. Метод +)
  2. Используется список переменных аргументов

Чтобы сделать это, вы, вероятно, сделаете что-то вроде этого:

+ (id)fooWithStuff:(id)stuff, ... NS_REQUIRES_NIL_TERMINATION {
  // the "+" means it's a class method
  // the "NS_REQUIRES_NIL_TERMINATION" is so that the compiler knows you have to use it like this:
  // foo = [ThisClass fooWithStuff:thing1, thing2, thing3, nil];
  // (IOW, there must be a "nil" at the end of the list)

  va_list args;  // declare a "variable list"
  va_start(args, stuff);  // the list starts after the "stuff" argument

  Foo *foo = [[Foo alloc] init];  // create a Foo object

  id nextStuff = stuff;  // this is the next stuff
  while(nextStuff != nil) { // while there is more stuff...
    [foo doSomethingWithStuff:nextStuff];  // do something with the stuff
    nextStuff = va_arg(args, id);  // get the next stuff in the list
    // the "id" means that you're asking for something the size of a pointer
  }
  va_end(args);  // close the argument list

  return [foo autorelease];  // return the Foo object

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...