ARC中的虚假va_list [英] fake va_list in ARC
问题描述
我需要在iOS应用程序中创建一个假的 va_list
来传递给NSString initWithFormat:arguments:
function ,这是我的代码:
I need to create in an iOS application a fake va_list
to pass to a NSString initWithFormat:arguments:
function, this is my code:
NSArray *fixedArguments = [[NSArray alloc] initWithArray:arguments];
NSRange range = NSMakeRange(0, [fixedArguments count]);
va_list fakeArgList = (va_list)malloc(sizeof(NSString *) * [fixedArguments count]);
__unsafe_unretained id *ptr = (__unsafe_unretained id *)fakeArgList;
[fixedArguments getObjects:ptr range:range];
content = [[NSString alloc] initWithFormat:outputFormat
arguments:(va_list)fakeArgList];
free(fakeArgList);
编译器在投射线上抱怨此消息:
The compiler complains with this message on the cast line:
error: cast of a non-Objective-C pointer type 'va_list' (aka 'char *') to '__unsafe_unretained id *' is disallowed with ARC
getObjects:range:
函数定义如下:
- (void)getObjects:(id __unsafe_unretained [])objects range:(NSRange)range;
我已经尝试了一切,但仍然无法摆脱这个错误......
I've tried everything but still can't get rid of this error...
是否有启用ARC的假冒 va_list
的解决方案?我做错了什么?
Is there a solution for creating a fake va_list
with ARC enabled? What am i doing wrong?
推荐答案
编辑:这不再有效。正如在最初的答案中所预见的那样,ABI似乎已经从这个答案中改变了
This no longer works. As foreseen in the initial answer, the ABI appears to have changed out from under this answer
玩了一下并让它起作用 - 双重检查泄漏或废弃的内存并没有看到任何内容。
Played around for a bit and got it to work -- Double checked for leaks or abandoned memory and didn't see any.
NSArray *fixedArguments = [[NSArray alloc] initWithObjects: @"foo", @"bar", @"baz", nil];
NSRange range = NSMakeRange(0, [fixedArguments count]);
NSMutableData* data = [NSMutableData dataWithLength: sizeof(id) * [fixedArguments count]];
[fixedArguments getObjects: (__unsafe_unretained id *)data.mutableBytes range:range];
NSString* content = [[NSString alloc] initWithFormat: @"1: %@ 2: %@ 3: %@" arguments: data.mutableBytes];
NSLog(@"%@", content);
我喜欢(ab)使用这样的NSMutableData来获取任意块上的保留/释放语义记忆 - 它不一定与手头的问题有关,但它是一个巧妙的小技巧。
I like to (ab)use NSMutableData like this to get retain/release semantics on an arbitrary chunk of memory -- It's not necessarily relevant to the issue at hand, but it's a neat little trick.
作为未来读者的一个注释:假装这样的va_list恰好使用适用于MacOS和iOS的当前ABI,但一般来说它不是便携式的,也不是一个好的方法。
As a note to future readers: Faking up a va_list like this happens to work with the current ABI for MacOS and iOS, but in general it's not portable, and not a good approach.
这篇关于ARC中的虚假va_list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!