0

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!

Brandon
  • 2,387
  • 13
  • 25
CarlosTheJackal
  • 220
  • 1
  • 14
  • 1
    For local values, no you cannot do this. You can though just do a simple if / else if / else on the string and take appropriate action. – vcsjones Jul 14 '14 at 21:30

2 Answers2

1

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
random
  • 8,568
  • 12
  • 50
  • 85
  • Thanks.. This is useful.. But I still don't think it will help me.. I'm trying to get a lua script to access an array by passing a string to Objective C.. I might have to use a brute force if/then to access it.. – CarlosTheJackal Jul 14 '14 at 21:36
1

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];
Brandon
  • 2,387
  • 13
  • 25