将NSArray内容转换为varargs(使用ARC)以用于NSString initWithFormat [英] Converting NSArray Contents to a varargs (With ARC) For Use With NSString initWithFormat
问题描述
我们今天有一些代码使用NSArray并将其作为参数列表传递给-[NSString initWithFormat:arguments],我们正在尝试使其与ARC一起使用.这是代码在使用
We have some code today that takes an NSArray and passes it as a argument list to -[NSString initWithFormat:arguments] and we're trying to get this to work with ARC. Here's the code were using
NSString* format = @"Item %s and Item %s"; // Retrieved elsewhere
NSArray* args = [NSArray arrayWithObjects:@"1", @"2", nil]; // Retrieved elsewhere
// http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html
char* argsList = (char*) malloc(sizeof(NSString*) * args.count);
[args getObjects:(id*) argsList];
NSString* message = [[[NSString alloc] initWithFormat:format arguments:argsList] autorelease];
free(argsList);
关于如何使此ARC兼容的任何建议?或者,我们甚至愿意采取更好的方法.
Any recommendations on how to make this ARC compliant? Or we're even open to a better way of doing it.
推荐答案
这仅适用于具有单个元素的数组
chrisco的答案一直很好,直到我开始使用64位体系结构进行编译.这导致了错误:
The answer by chrisco was working well, until I went to compile with 64-bit architecture. This caused an error:
EXC_BAD_ADDRESS类型EXC_I386_GPFLT
EXC_BAD_ADDRESS type EXC_I386_GPFLT
解决方案是使用稍微不同的方法将参数列表传递给方法:
The solution was to use a slightly different approach for passing the argument list to the method:
+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments;
{
__unsafe_unretained id * argList = (__unsafe_unretained id *) calloc(1UL, sizeof(id) * arguments.count);
for (NSInteger i = 0; i < arguments.count; i++) {
argList[i] = arguments[i];
}
NSString* result = [[NSString alloc] initWithFormat:format, *argList] ;// arguments:(void *) argList];
free (argList);
return result;
}
这篇关于将NSArray内容转换为varargs(使用ARC)以用于NSString initWithFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!