0
我在某些方面對Objective-C很新穎,所以我想問一下我應該如何讓方法返回對象本身。讓我給個例子:Objective C +(id)方法
在NSArray
你可以做[NSArray arrayWithObjects:bla,bla,nil];
我如何作出這樣的一種方法,以我自己的類?
我在某些方面對Objective-C很新穎,所以我想問一下我應該如何讓方法返回對象本身。讓我給個例子:Objective C +(id)方法
在NSArray
你可以做[NSArray arrayWithObjects:bla,bla,nil];
我如何作出這樣的一種方法,以我自己的類?
有與該方法會在兩個主要方面:
+
方法)要使它,你可能會這樣做:
+ (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
}
現在我非常感謝!我總是想知道爲什麼我必須把零結束! –
@Samuli yep,'nil'讓列表知道何時停止。它被稱爲「哨兵」:) –