user859194
user859194

Reputation: 103

Naming a newly-created instance based on user input

I have a class (let's call it foo.m) and my main barAppdelegate.m. In my delegate, I want to create an instance of foo.m dynamically based on the user input (i.e., the name of this instance should be what the user enters) and I need to keep track of lots of these.

Upvotes: 0

Views: 91

Answers (3)

jscs
jscs

Reputation: 64002

There's absolutely no reason in Objective-C to specify the name of a variable at runtime. Variables are for you, the programmer (and the compiler). You need to slightly rethink your program.

You need every instance of your Foo class to be associated with a user-entered string. You should therefore give the class an instance variable to hold that string. When you create the objects, put them into a collection -- either, as PengOne suggests, a dictionary where you can again access them by the provided string, or simply an array.

If you really think that you will need to retrieve the instances primarily by that string, then a dictionary is a good choice. If you will only occasionally need to get at the instances that way, use an array and have a look at indexOfObjectPassingTest:

NSUInteger idx = [myArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    if( [[obj name] isEqualToString:stringToTest] ){
        *stop = YES;
        return YES;
    }
}];

Upvotes: 2

sach
sach

Reputation: 1069

ClassName myClass = NSClassFromString (@"classname");

ClassName *object = [[myClass alloc] init];

Upvotes: 0

PengOne
PengOne

Reputation: 48398

The simplest solution is to create an NSMutableDictionary in which to store the instances of foo that you create (these are the objects) and set the name to be the key as an NSString.

Upvotes: 2

Related Questions