2014-03-28 139 views
0

遇到了一些问题。我有一个.plist文件,其中包含下一个数据http://imageshack.com/a/img856/1421/xvzm.png从.plist文件中读取

所以我不明白,我如何需要读取第一个数组,比在数组读取字典。或者,也许需要重写文件,并更改根键来输入字典,读这样的:

NSString *errorDesc = nil; 
NSPropertyListFormat format; 
NSString *plistPath; 
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
    NSUserDomainMask, YES) objectAtIndex:0]; 
plistPath = [rootPath stringByAppendingPathComponent:@"Data.plist"]; 
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) { 
    plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; 
} 
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; 
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization 
    propertyListFromData:plistXML 
    mutabilityOption:NSPropertyListMutableContainersAndLeaves 
    format:&format 
    errorDescription:&errorDesc]; 
if (!temp) { 
    NSLog(@"Error reading plist: %@, format: %d", errorDesc, format); 
} 
self.personName = [temp objectForKey:@"Name"]; 
self.phoneNumbers = [NSMutableArray arrayWithArray:[temp objectForKey:@"Phones"]]; 

回答

1

您可以通过下面的代码做到这一点:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; 
NSArray *dataArray = [NSArray arrayWithContentsOfFile:plistPath]; 

此数组将包含所有的字典,你可以让他们喜欢:

NSDictionary *dict = [dataArray objectAtIndex:0]; 
+1

除本扔出来的代码加载从Documents文件夹(如果存在)。 – rmaddy

+1

它实际上并没有回答这个问题。问题是关于从数组中获取所需的数据。 – rmaddy

+0

'objectAtIndex:'是一个旧的语法,有一些更新的 –

1
SString *plistFile = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; 
NSArray *array = [NSArray arrayWithContentsOfFile:plistFile]; 

for(NSDictionary *dictionary in array) { 
    NSLog(@"%@", dictionary); 
} 

NSDictionary *item0 = array[0]; 
NSString *imageName = item[0][@"name"]; 
+1

这抛出了代码从文档中加载文件文件夹,如果它存在。 OP可能仍然需要该代码。 – rmaddy

+0

OP的代码先查看Documents文件夹,然后使用资源束作为后备。为了OP,我指出这个答案消除了这个逻辑。 – rmaddy