Search code examples
iosobjective-creflectionnsarrayintrospection

How to access an instance variable by an NSString generated at run-time (reflection)


I've got the following little code conundrum..

- (void) transmitArray {

    NSString* arrayName = @"array1";

    NSArray* array1 = [NSArray arrayWithObject:@"This is Array 1"];
    NSArray* array2 = [NSArray arrayWithObject:@"This is Array 2"];

    NSMutableArray* targetArray = [NSMutableArray arrayWithCapacity:1];

}

Is there a way to use the string "array1" to access the NSArray 'array1' so I can copy it into the target array.. And therefore, if the string read "array2", I'd be able to access the second array?

I read about using NSSelectorFromString to create a selector, and that this technique was called 'introspection', but other than that I'm stumped..

Hope someone can help!


Solution

  • Not really. If it were a instance variable of the class (generally known as a property) then you could use introspection to inspect the object and get/set the needed variables. You can can use the KVO methods

    setValue:(id) ForKeyPath:(NSString *)
    

    and

    valueForKeyPath:(NSString *)
    

    to access them

    However you can't do that with local variables declared inside of an instance method (directly). I would suggest populating a dictionary with your arrays and then using it as a lookup table

    NSMutableDictionary *arrays = [[NSMutableDictionary alloc] init];
    
    NSArray *array1 = @[@"This is Array 1"];
    [arrays setObject:array1 forKey:@"array1"];
    
    NSArray *array2 = @[@"This is Array 2"];
    [arrays setObject:array1 forKey:@"array2"];
    
    //grab a copy of array1
    NSArray *targetArray = [arrays[@"array1"] copy];