0

I need a method for generating string from the format-string and it's arguments inside NSArray but I did't find any working solution on the StackOverflow. They don't build nor throw exceptions (first, second).

Community
  • 1
  • 1
ajjnix
  • 462
  • 3
  • 17
  • This is still a badly worded duplicate question. You should add your answer on to one of the questions you referenced, ideally the first one... – Wain Jan 27 '16 at 14:05
  • Closed because of https://stackoverflow.com/a/35089943/ – jscs Jun 11 '17 at 17:01

1 Answers1

3

So I write my solution and I want to share it with 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];
    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:@"@%zd@0:%zd", offsetReturnType, sizeptr];
    for (NSInteger i = 2; i < sumArgInvoke; i++) {
        [mstring appendFormat:@"@%zd", sizeptr * i];
    }
    return [NSMethodSignature signatureWithObjCTypes:[mstring UTF8String]];
}

@end
ajjnix
  • 462
  • 3
  • 17
  • `NSNumber *numb = arrayArguments[i];` can be more generic as you don't know it's an array of numbers. interesting approach though – Wain Jan 27 '16 at 14:05
  • sorry, I copy paste code from my project... yes, it need replace at id (edit) – ajjnix Jan 27 '16 at 14:08