2016-01-27 69 views
0

我需要从格式字符串生成字符串的方法,它的内部NSArray的论点,但我我以前不觉得在StackOverflow的任何可行的解决方案。他们不建,也不抛出异常(firstsecond)。的NSString stringWithFormat和NSArray的

+0

这仍然是一个严重的措辞重复的问题。您应该添加你的答案到你提到的问题,理想的第一个一个... – Wain

+0

关闭,因为https://stackoverflow.com/a/35089943/ –

回答

3

所以,我写我的解决方案,我想与你分享。

@implementation NSString (AX_NSString) 

+ (instancetype)ax_stringWithFormat:(NSString *)format array:(NSArray *)arrayArguments { 
    NSMethodSignature *methodSignature = [self ax_generateSignatureForArguments:arrayArguments]; 
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature]; 

    [invocation setTarget:self]; 
    [invocation setSelector:@selector(stringWithFormat:)]; 

    [invocation setArgument:&format atIndex:2]; 
    for (NSInteger i = 0; i < [arrayArguments count]; i++) { 
     id obj = arrayArguments[i]; 
     [invocation setArgument:(&obj) atIndex:i+3]; 
    } 

    [invocation invoke]; 

    __autoreleasing NSString *string; 
    [invocation getReturnValue:&string]; 

    return string; 
} 

//https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html 
+ (NSMethodSignature *)ax_generateSignatureForArguments:(NSArray *)arguments { 
    NSInteger count = [arguments count]; 
    NSInteger sizeptr = sizeof(void *); 
    NSInteger sumArgInvoke = count + 3; //self + _cmd + (NSString *)format 
    NSInteger offsetReturnType = sumArgInvoke * sizeptr; 

    NSMutableString *mstring = [[NSMutableString alloc] init]; 
    [mstring appendFormat:@"@%[email protected]:%zd", offsetReturnType, sizeptr]; 
    for (NSInteger i = 2; i < sumArgInvoke; i++) { 
     [mstring appendFormat:@"@%zd", sizeptr * i]; 
    } 
    return [NSMethodSignature signatureWithObjCTypes:[mstring UTF8String]]; 
} 

@end 
+0

'的NSNumber *麻木= arrayArguments的[I]'可以更通用,因为你不知道它是一组数字。有趣的做法,虽然 – Wain

+0

对不起,我从我的项目中复制粘贴代码...是的,它需要替换id(编辑) – ajjnix