fake va_list in ARC

后端 未结 2 1618
臣服心动
臣服心动 2020-12-03 08:07

I need to create in an iOS application a fake va_list to pass to a NSString initWithFormat:arguments: function, this is my code:

NS         


        
2条回答
  •  没有蜡笔的小新
    2020-12-03 08:26

    EDIT: 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);
    

    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.

    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.

提交回复
热议问题