0

Basically I have an array of nsstring objects like 'A',L,L,A,H,A,B,A,D. The output should be NSDICTIONARY 0,3,5,7 FOR KEY A, 1,2 FOR KEY L 4 FOR KEY H 6 FOR KEY B 8 FOR KEY D.

Desparado_
  • 605
  • 6
  • 7
  • what do you mean by 'output'? you mean as an NSLog to the screen? or you just want to know the code necessary to store what you described in a data structure? – abbood Feb 21 '13 at 04:33
  • Just want to know the approach. I tried it like for (id object in [MyArray reverseObjectEnumerator]). But does not seem to work – Desparado_ Feb 21 '13 at 04:42

2 Answers2

0

It's a simple for-in loop which could look a little like this:

- (NSDictionary*)dictionaryFromArrayOfStrings:(NSArray*)array {
    int idx = 1;
    NSMutableDictionary *retVal = @{}.mutableCopy;
    for (NSString *char in array) {
        //reverse them for a dictionary of NSNumbers for a set of NSString keys
        [retVal setObject:char forKey:@(idx)];
        idx++;
    }
    return retVal;
}
CodaFi
  • 43,043
  • 8
  • 107
  • 153
  • interesting.. never seen `@{}.mutableCopy` before.. is that same as initializing an NSMutableDictionary like so: `NSMutableDictionary *retval = [NSMutableDictionary dictionaryWithCapacity:0]`? – abbood Feb 21 '13 at 04:49
  • Also wy did you use forKey:@(idx) as opposed to forKey:idx? – abbood Feb 21 '13 at 04:54
  • New features in Xcode. The first is a dictionary literal that I'm messaging for a mutable copy (therefore I get an NSMutableDictionary). The second is boxing: take any 'ol number (int, float, long, etc.) and box it between @() and it gets converted to an NSNumber. – CodaFi Feb 21 '13 at 05:51
  • interesting.. do you have a link/tutorial for at least this new feature? – abbood Feb 21 '13 at 06:16
0

you cannot have an array that has keys and values (ie NSDictonary 0,3,5,7 for key A).. you that can be done with an NSDictionary, further, if you only have a set of values.. then you should use an array for that

this is what you should do:

NSDictionary* parent = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:@"A",@"L",@"L",@"A",@"H",@"A",@"B",@"A",@"D", nil], @"A", [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:[[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], nil]], @"L", [NSNUmber numberWithInt4], @"H", [NSNumber numberWithInt:6], @"B", [NSNumber numberWithInt:8], @"D",nil]; 
abbood
  • 23,101
  • 16
  • 132
  • 246
  • I don't think my question was properly formed. I want to have array of index positions as the object and character as a key. So if A is the key the object for the key would be an array having values '0','3''5''7' – Desparado_ Feb 21 '13 at 04:55