如何将零个字符串列表传递给Objective-C函数? [英] How do I pass a nil-terminted list of strings to an Objective-C function?

查看:57
本文介绍了如何将零个字符串列表传递给Objective-C函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数[NSArray arrayWithObjects:foo,bar,nil]将以nil终止的字符串列表传递给函数.

The function [NSArray arrayWithObjects:foo, bar, nil] passes a nil-terminted list of string to a function.

如果我想编写类似的函数,则声明是什么样的,以及如何遍历字符串?

If I want to write a similar function, what does the declaration look like, and how do I iterate through the strings?

推荐答案

我引用

I quote http://developer.apple.com/mac/library/qa/qa2005/qa1405.html, which contains the full truth.

这是一个Objective-C类别的示例,其中包含一个追加了可变参数的方法 NSMutableArray实例的自变量以零结尾的列表中的所有对象:

Here's an example of an Objective-C category, containing a variadic method that appends all the objects in a nil-terminated list of arguments to an NSMutableArray instance:

#import <Cocoa/Cocoa.h>

@interface NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...;  // This method takes a nil-terminated list of objects.

@end

@implementation NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...
{
id eachObject;
va_list argumentList;
if (firstObject)                      // The first argument isn't part of the varargs list,
  {                                   // so we'll handle it separately.
  [self addObject: firstObject];
  va_start(argumentList, firstObject);          // Start scanning for arguments after firstObject.
  while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
    [self addObject: eachObject];               // that isn't nil, add it to self's contents.
  va_end(argumentList);
  }
}

@end

这篇关于如何将零个字符串列表传递给Objective-C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆