Lordof Theflies
Lordof Theflies

Reputation: 301

dynamic naming of fields in nsmutable array?

I hope i can explain this clearly. I have a NSMutableArray * myMut. I have user input in the form of an NSString * anyoldString. I have user input of some numeric values stored in the variable someNumber;

As users input their string and values, I want to update myMut, and name the fields anyoldString

like this: myMut.anyoldString=someNumber; depending on the user's input, the name will be different of course

i'm new to objective c.

in Matlab, I would do this:

myMut.(anyoldString)=someNumer. 

I know that's too easy for objective c! but any fast way to do this??

Upvotes: 0

Views: 155

Answers (1)

Williham Totland
Williham Totland

Reputation: 29019

You'll probably want to do something like so:

NSMutableDictionary *myMutableDictionary; // A mutable **dictionary**, not an array!
NSInteger someNumber; // filled by the number
NSString *key; // filled by anyOldString

[myMutableDictionary setObject:[NSNumber numberWithInteger:someNumber] forKey:key];

NSArray and friends aren't associative; but indexed. What you want is NSDictionary and friends; your friendly neighborhood key-value mapping!

Edit: For funsies; getting someNumber back out, given anyOldString:

NSMutableDictionary *myMutableDictionary; // The same dictionary as above
NSInteger someNumber; // out number
NSString *key; // filled by anyOldString

NSNumber *storedNumber = [myMutableDictionary objectForKey:key];

if (storedNumber) {
  someNumber = [storedNumber integerValue];
} else {
  someNumber = APPLICATION_APPROPRIATE_DEFAULT_VALUE;
}

Upvotes: 2

Related Questions