Pregunta

I have tried my best to search for the answers to add NSMutableDictionary to NSMutableArray. Unfortunately, they all asked me to use "[allValues]" which is not what I want.

Here is the issue,

In the header file, I defined,

NSMutableArray *arData;

And in the m file,

arData = [[NSMutableArray alloc] init];

NSMutableDictionary *mutableDictionary5 = [[NSMutableDictionary alloc]init];

for (i=0;i<[[[self rssParser]rssItems]count];i++)
{

    Lat = [[[[[self rssParser]rssItems]objectAtIndex:i]lat] doubleValue];
    Lng = [[[[[self rssParser]rssItems]objectAtIndex:i]lng] doubleValue];
    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(Lat, Lng);
    marker.title = [[[[self rssParser]rssItems]objectAtIndex:i]header];

[mutableDictionary5 setObject:marker.title forKey:@"title"];

[arData setValue:[mutableDictionary5 valueForKey:@"title"] forKey:@"title"];
}

The "arData" only gets the last value of [[[[self rssParser]rssItems]objectAtIndex:i]header].And I am sure mutableDictionary5 gets all the value since I have put the following at the end of the code,

 NSLog(@"mutableDictionary5 values=%@",[mutableDictionary5 allValues]);

It prints all the value of the title.

I understand it shouldn't be setvalue, however, I tried to use [mutableDictionary5 allValues], "addobjects", "allkeys". They are not working. What should I do to let the NSMutableArray arData to add all values of title with "title" as the key? thanks.

Sorry for my bad English which is not my native language.

¿Fue útil?

Solución

You erroneously use setValue instead of addObject.

[arData addObject:mutableDictionary5]; 

This will work if you alloc init a new dictionary inside the loop.
If you want to reduce the array to just titles do this after the loop:

NSArray *titleArray = [arData valueForKeyPath:@"title"]; 

Now you have an array containing just titles.

BTW, you could make some effort to invent better variable names. Note that by convention in Objective-C variable names start with low cap while class names are capitalized.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top