如何使用Objective C读取Plist数据?

时间:2015-12-28 13:34:21

标签: ios objective-c json plist

我已将JSON数据存储到Plist中。每当我想查看我存储的数据时,我都会获取路径详细信息并找到我的机器,然后我才能看到。我需要在使用目标C存储后读取数据。

NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
 NSDictionary *response = JSON[@"response"];
 NSArray *keys = [response allKeys];

 NSMutableArray *objects = [NSMutableArray new];
 for (NSString *key in keys) {
     NSMutableDictionary *object = response[key];
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subject = %@",object[@"subject"]];
     NSArray *objectsWithSameSubject = [objects filteredArrayUsingPredicate:predicate];
     NSInteger subjects = [object[@"subject"] integerValue];
     if (subjects > 0) {

         NSMutableArray *Objects_Subjectcount = [NSMutableArray new];
         [object setObject:Objects_Subjectcount forKey:@"Objects_Subjectcount"];
         for (NSInteger i = 0; i < subjects; i++) {
             [Objects_Subjectcount addObject:object];// object or anything you need

         }
     }
     [objects addObject:object];
 }

 NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsPath = paths.firstObject;
 NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"File.plist"];
 NSError *writeError = nil;
 NSDictionary *finalDict = @{@"Objects": objects};
 NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
 if(plistData){
     [plistData writeToFile:plistPath atomically:YES];
 }
 else {
     NSLog(@"Error in saveData: %@", error);
 }

enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个:

  NSError *error = nil;    
    NSData * tempData = [[NSData alloc] initWithContentsOfFile:@"File.plist"];
    NSPropertyListFormat plistFormat = nil;
    NSDictionary *temp = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NSPropertyListXMLFormat_v1_0 error:&error];
  • 注意:

    当您使用NSPropertyListSerialization阅读数据时,您不必通过NSPropertyListFormat。您要么通过nil,要么传递NSPropertyListFormat的地址。

希望这会有所帮助。

答案 1 :(得分:1)

获得plist文件的正确路径后,您可以通过以下方式阅读:

NSMutableDictionary *plistDic = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

int value = [[plistDic objectForKey:@”value”] intValue];  //to get a int value for value for example

并写给plist:

[plistDic setObject:[NSNumber numberWithInt:2] forKey:@”value”];

[plistDic writeToFile: path atomically:YES];