开发者

Convert dictionary items from plist to NSArray

I have a plist with the following architecture/structure:

dictionary
   key1
    item1
   key2
    item2
   key3
    item3
dictionary
   ...

and i want to load item (item1) for the first key (key1) of every dictionary to an NSArray, so that i can load the nsarray into a UITableView.

i cam to this point:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *d开发者_如何转开发ocumentsDirectory = [paths objectAtIndex:0];

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];

    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];

and then i wanted to add something like this:

tablearray = [array objectsForKey:@"key1"];

but that doesn't exist as command. Seems like i need some help there... :)


You can loop over the Array and add the Objekts that way:

NSMutableArray *tablearray = [NSMutableArray arrayWithCapacity:[array count]];
for (NSDictionary *dict in array) {
    [tablearray addObject:[dict objectForKey:@"key1"]];
}


Apple provides pList programming guide which describes how to read from a pList and also writes into it. You can go throug it.

We will get the data from the pList as NSData and convert it into NSDictionary, by using the following method,

NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];

NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization 
            propertyListFromData:plistXML 
            mutabilityOption:NSPropertyListMutableContainersAndLeaves 
            format:&format 
            errorDescription:&errorDesc]; 

you can add the response dictionary intro an array using the

NSMutableArray * myArray = [NSMutableArray alloc] init];

//temp is the response dictionary
NSArray * myKeys = [temp allKeys];
for (int index = 0; index<[myKeys count]; index++) {


id value = [temp valueForKey:[myKeys objectAtIndex:index]];
[myArray addObject:value];

}

use the myArray now.

I think this is what you needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜