Reputation: 53
I have stored JSON data Into within Plist. Whenever I want to see my stored data I am taking path details and find into my machine then only I can see. I need to read data after storage using objective 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);
}
Upvotes: 1
Views: 3279
Reputation: 10959
Try this:
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];
Note :
when you read data using NSPropertyListSerialization
you dont have to pass NSPropertyListFormat
. you either pass nil
or pass the address for NSPropertyListFormat
.
Hope this will help.
Upvotes: 1
Reputation: 11201
Once you have the right path to the plist file, you can read it by:
NSMutableDictionary *plistDic = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
int value = [[plistDic objectForKey:@”value”] intValue]; //to get a int value for value for example
and to write to plist:
[plistDic setObject:[NSNumber numberWithInt:2] forKey:@”value”];
[plistDic writeToFile: path atomically:YES];
Upvotes: 1