iOS 多参数 ...NS_REQUIRES_NIL_TERMINATION 的写法
生活随笔
收集整理的這篇文章主要介紹了
iOS 多参数 ...NS_REQUIRES_NIL_TERMINATION 的写法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.很早就看到項目里面有下面這樣的寫法
1 - (id) initWithTitle:(NSString *)title items:(MXContextMenuItem *)item, ... NS_REQUIRES_NIL_TERMINATION;2.查了點資料,自己練習了下,試著寫了個
1 //.h 2 - (NSString *)addMoreArguments:(NSString *)firstStr,...NS_REQUIRES_NIL_TERMINATION; 3 4 //.m 5 - (NSString *)addMoreArguments:(NSString *)firstStr,... 6 { 7 va_list args; 8 va_start(args, firstStr); // scan for arguments after firstObject. 9 10 // get rest of the objects until nil is found 11 NSMutableString *allStr = [[[NSMutableString alloc] initWithCapacity:16] autorelease]; 12 for (NSString *str = firstStr; str != nil; str = va_arg(args,NSString*)) { 13 [allStr appendFormat:@"* %@ ",str]; 14 } 15 16 va_end(args); 17 return allStr; 18 } 19 20 //test 21 NSString *str = [self addMoreArguments:@"hello",@"world",@"this",@"is",@"a",@"test", nil]; 22 NSLog(@"str = %@",str); 23 //output: str = * hello * world * this * is * a * test3.官方有個例子挺好的,實現NSMutableArray的appendObjects...
appendObjects實現
code:
1 #import <Cocoa/Cocoa.h> 2 3 @interface NSMutableArray (variadicMethodExample) 4 5 - (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects. 6 7 @end 8 9 @implementation NSMutableArray (variadicMethodExample) 10 11 - (void) appendObjects:(id) firstObject, ... 12 { 13 id eachObject; 14 va_list argumentList; 15 if (firstObject) // The first argument isn't part of the varargs list, 16 { // so we'll handle it separately. 17 [self addObject: firstObject]; 18 va_start(argumentList, firstObject); // Start scanning for arguments after firstObject. 19 while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id" 20 [self addObject: eachObject]; // that isn't nil, add it to self's contents. 21 va_end(argumentList); 22 } 23 } 24 25 @end?
轉載于:https://www.cnblogs.com/ubersexual/p/3526199.html
總結
以上是生活随笔為你收集整理的iOS 多参数 ...NS_REQUIRES_NIL_TERMINATION 的写法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1-17
- 下一篇: 文件的输入/输出操作