objective c - NSString stringWithFormat and NSArray -
this question has answer here:
i need method generating string format-string , it's arguments inside nsarray did't find working solution on stackoverflow. don't build nor throw exceptions (first, second).
so write solution , want share you.
@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]; (nsinteger = 0; < [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:@"@%zd@0:%zd", offsetreturntype, sizeptr]; (nsinteger = 2; < sumarginvoke; i++) { [mstring appendformat:@"@%zd", sizeptr * i]; } return [nsmethodsignature signaturewithobjctypes:[mstring utf8string]]; } @end
Comments
Post a Comment