Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

iphone - Not able to write to Plist

I have a very basic question about how to write to a plist. I added a "Here.plist" file to my resources folder. The following is my code:

NSString *path = [[NSBundle mainBundle]pathForResource:@"Here" ofType:@"plist"];

NSArray *array = [[NSArray alloc]initWithObjects:@"First", @"Second", @"Third", nil];

[array writeToFile:path atomically:YES];

"Here.plist" is still empty after executing the code. I even tried using a NSDictionary as follows:

NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"firstValue", @"First", @"secondValue", @"Second", @"thirdValue", @"Third", nil];

[dict writeToFile:path atomically:YES];

I went through many tutorials and forums but its just not working for me. What am i doing wrong? Losing my head over this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't write into the bundle. Try writing into the documents directory. For example:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *array = [[NSArray alloc]initWithObjects:@"First", @"Second", @"Third", nil];
[array writeToFile:[documentsDirectory stringByAppendingPathComponent:@"Here.plist" atomically:YES];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...