views:

808

answers:

2

Hi, I have the next question,

if possible to write in a .plist datas in runtime, because my app make a lot of connections and i would like to save this datas (after parsing) in a plist, for later read this datas.

Is it possible? because i'm trying and for the moment i can't.

Thanks.

+3  A: 

Yes. To save a property list:

NSString * error;
NSData * data = [NSPropertyListSerialization dataFromPropertyList:yourPlist format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
[data writeToFile:pathToYourFile atomically:YES];

yourPlist must be a kind of NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary object.

To read your property list.

NSString * error;
NSData * data = [NSData dataWithContentsOfFile:pathToYourFile];
yourPlist = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
Marco Mustapic
But I'm trying to take the data, from the conection, parse and then(i have the good values that i want) write this values in a Dictionary and insert in the .plist that will be an array of dictionaries.
You would use your top-level array object as 'yourPlist' in Marco's example. The API is confusingly named (in my opinion at least) in that the 'property list' referred to by dataFromPropertyList is really just an object that conforms to the property list type requirements.
smorgan
Then if i create a plist named "Data.plist" this should run:NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; NSString *path = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; NSString * error; NSString * hola = @"123"; NSData * data = [NSPropertyListSerialization dataFromPropertyList:hola format:NSPropertyListXMLFormat_v1_0 errorDescription: [data writeToFile:path atomically:YES];
I'm sorry, ONLY THIS:NSString *path = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; NSString * error; NSString * hola = @"123"; NSData * data = [NSPropertyListSerialization dataFromPropertyList:hola format:NSPropertyListXMLFormat_v1_0 errorDescription: [data writeToFile:path atomically:YES];
+1  A: 

Use this method:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

The docs explain it here: http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDictionary/writeToFile:atomically:

You just create the dictionary, then save it to the file using that method.

Dan Lorenc
Yup. And to read the plist you can use -[NSDictionary initWithContentsofFile:].The NSPropertyListSerialization class is useful too, but mainly just when you want to operate on property lists as raw data, not in files.
Jens Alfke