Objective C +(id)方法

时间:2011-06-26 16:01:38

标签: objective-c

我在某些方面对Objective-C很新,所以我想问一下如何制作返回对象本身的方法。让我举个例子:

NSArray中,您可以执行[NSArray arrayWithObjects:bla,bla,nil];

我如何为自己的班级制作这种方法?

1 个答案:

答案 0 :(得分:4)

该方法有两个主要方面:

  1. 这是一种类方法(即+方法)
  2. 它使用可变参数列表
  3. 要做到这一点,你可能会做这样的事情:

    + (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
    
    }