Converting NSArray Contents to a varargs (With ARC) For Use With NSString initWithFormat

前端 未结 6 932
广开言路
广开言路 2021-02-19 13:43

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 th

6条回答
  •  有刺的猬
    2021-02-19 14:23

    This only works for arrays with a single element

    The answer by chrisco was working well, until I went to compile with 64-bit architecture. This caused an error:

    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;
    }
    

提交回复
热议问题