0
votes

I am trying to put an NSDictionary within an NSArray. My aim is that each object in the array will be a dictionary with two keys and two objects. So they keys for the Dictionary will be called "TITLE" and "AUTHOR" and each will have a value, and that whole thing will be stored in an NSMutableArray object.

Here is the code I have (dataSource is an array with a list of titles, author is an array with a list of corresponding authors, and searchedData is the array I want the dictionary to go into an object of):

for (int i = 0; i<[dataSource count]-1; i++) {
    NSLog(@"in");
    NSString *authorString = [NSString stringWithFormat:@"%@",[author objectAtIndex:i]];
    NSString *titleString = [NSString stringWithFormat:@"%@",[dataSource objectAtIndex:i]];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:titleString, @"TITLE",authorString,@"AUTHOR", nil];
    [searchedData addObject:dict];
}

I tried this but either it doesn't work, or I don't know how to read the data from the dictionary within the array. I want to be able to say "get the object for key "title" from the dictionary in object n of searchedData, but I don't know how.

Thanks so much!!!

Luke

2
You cannot add objects to an NSArray or an NSDictionary. You have to create each type with whatever you want it to contain, then that is it. They are immutable objects. If you want to change them, you have to use NSMutableArray or NSMutableDictionary. - gurooj
sorry, the array is mutable (but the dictionary isn't, does that matter?) - Luke Baumann
where do you create the searchedData array? - James P
Sorry, I edited the question to include that. - Luke Baumann

2 Answers

2
votes

Tried this?

NSDictionary *nthDict = [mutableArray objectAtIndex:n];
NSString *title = [nthDict objectForKey:@"TITLE"];
NSString *author = [nthDict objectForKey:@"AUTHOR"];
1
votes

Your for loop skips the last element in the dataSource array. Other than that I can't see any problems with your code. Adding an immutable dictionary to an array is fine, retrieving it like H2CO3 shows is also ok.