Reputation: 1162
I have a json data to show some infos.. but i should generate "a file" to save these infos to my iPhone. Ideas?
- (void)showInfos {
NSMutableDictionary *infoDictionary = [[NSMutableDictionary alloc]init];
[infoDictionary setObject:self.totalDuration.text forKey:@"totalFrames"];
NSMutableArray *nodesArray = [[NSMutableArray alloc]init];
[nodesArray addObject:@{@"x":@(_zeroButton.frame.origin.x),@"y":@(_zeroButton.frame.origin.y),@"frame":self.zeroBtnLbl.text}];
[nodesArray addObject:@{@"x":@(_firstButton.frame.origin.x),@"y":@(_firstButton.frame.origin.y),@"frame":self.firstBtnLbl.text}];
[nodesArray addObject:@{@"x":@(_secondButton.frame.origin.x),@"y":@(_secondButton.frame.origin.y),@"frame":self.secondBtnLbl.text}];
[nodesArray addObject:@{@"x":@(_thirdButton.frame.origin.x),@"y":@(_thirdButton.frame.origin.y),@"frame":self.thirdBtnLbl.text}];
[nodesArray addObject:@{@"x":@(_fourthButton.frame.origin.x),@"y":@(_fourthButton.frame.origin.y),@"frame":self.fourthBtnLbl.text}];
[infoDictionary setObject:nodesArray forKey:@"nodes"];
NSLog(@"dicArray:%@",infoDictionary);
NSData *data = [NSJSONSerialization dataWithJSONObject:infoDictionary options:kNilOptions error:nil];
NSArray *retDicArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"retDicArray:%@",retDicArray);
}
Upvotes: 0
Views: 1356
Reputation: 677
Do you really need to save it into a file or you just want to serialize the information into the app?
Personally I often use the NSUserDefaults to save simple user information inside the app.
For example, if you want to store an integer:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:newDistance forKey:@"myInteger"];
[defaults synchronize];
Then when you want to retrieve it, simply do:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int myInteger = (int)[defaults integerForKey:@"myInteger"];
You can store also NSArray, so it should work for you.
If you have more complicated structure to serialize you can use Core Data but it's a lot more complicated.
Upvotes: 0
Reputation: 107201
You can write that data to file using writeToFile:atomically: method of NSData
.
NSData *data = [NSJSONSerialization dataWithJSONObject:infoDictionary options:kNilOptions error:nil];
NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [docDir stringByAppendingPathComponent:@"MyJSONFile.json"];
[data writeToFile:filePath atomically:YES];
Upvotes: 3