CarlosTheJackal
CarlosTheJackal

Reputation: 230

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!

Upvotes: 0

Views: 53

Answers (2)

Brandon
Brandon

Reputation: 2427

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

Upvotes: 1

random
random

Reputation: 8608

If you have array1 declared as a property you can do it like this:

#import "ViewController.h"

@interface ViewController ()

@property NSArray *array1;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.array1 = [NSArray arrayWithObjects:@"Hello", @"world!", nil];

    NSArray *array2 = [self valueForKeyPath:@"array1"];

    NSLog(@"%@", array2);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Upvotes: 1

Related Questions