0

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

4
  • 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. Commented Feb 16, 2012 at 21:12
  • sorry, the array is mutable (but the dictionary isn't, does that matter?) Commented Feb 16, 2012 at 21:27
  • where do you create the searchedData array? Commented Feb 16, 2012 at 21:44
  • Sorry, I edited the question to include that. Commented Feb 16, 2012 at 22:36

2 Answers 2

2

Tried this?

NSDictionary *nthDict = [mutableArray objectAtIndex:n];
NSString *title = [nthDict objectForKey:@"TITLE"];
NSString *author = [nthDict objectForKey:@"AUTHOR"];
Sign up to request clarification or add additional context in comments.

3 Comments

Hi! thanks, but that returns (null) for each string. Is this a problem with how the NSDictionary is inserted into the NSMutableArray, or a problem with retrieving it?
@LukeBaumann: If I were a betting man, I'd say it's likely a problem with the NSMutableArray itself being nil.
Thanks its working now. The problem was that I forgot to initialize the array (doh!).
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.