iPhone SDK:如何正确地将用户输入的信息保存到 .plist 或其他文件中?
我已经浏览了 SDK 文档和其他提出的问题,但我仍然对到底如何做到这一点感到有点困惑。我之前一直在使用以下代码,尽管它没有给出 .plist 文件的预期结果。除了在 .m 文件中的此代码的头文件中提到 IBAction 之外,还有其他需要添加的内容或我应该采取的另一种方法吗?谢谢!
我的代码:
- (IBAction)fedDog {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"dogsFedDays.plist"];
NSMutableArray *dogsFedSave = [NSMutableArray arrayWithCapacity: 100];
for (int i = 0; i < 100; i++) {
NSDictionary *myDict = [[NSDictionary alloc] initWithObjectsAndKeys:
date[i], @"string",
fed[i], @"Yes",
nil];
[dogsFedSave addObject:myDict];
[myDict release];
}
if (![dogsFedSave writeToFile:path atomically:YES])
NSLog(@"not successful in completing this task");
}
I've looked through the SDK documentation and through other questions that have been asked, and I am still a little confused on how exactly to do this. I had been previously been working with the following code, though it does not give the desired result of a .plist file. Besides mentioning the IBAction in the header files in this code in the .m file, is there anything else that needs to be added or anothe method I should be taking? Thanks!
My Code:
- (IBAction)fedDog {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"dogsFedDays.plist"];
NSMutableArray *dogsFedSave = [NSMutableArray arrayWithCapacity: 100];
for (int i = 0; i < 100; i++) {
NSDictionary *myDict = [[NSDictionary alloc] initWithObjectsAndKeys:
date[i], @"string",
fed[i], @"Yes",
nil];
[dogsFedSave addObject:myDict];
[myDict release];
}
if (![dogsFedSave writeToFile:path atomically:YES])
NSLog(@"not successful in completing this task");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设 -writeToFile 返回 NO 所以你会看到你的 NSLog 语句(如果我错了,请纠正我)。如果是这种情况,那么问题一定是您的 date 数组或 fed 数组中的某些对象不是属性列表允许的任何对象类型,其中包括: NSString、NSData、NSArray 或 NSDictionary。不允许 NSNull。来自 writeToFile 的文档:
I'm assuming that -writeToFile is returning NO so you're seeing your NSLog statement (correct me if I'm wrong). If that's the case, then the issue must be that some object in either your date array, or fed array is not any of the allowed object types for property lists which includes: NSString, NSData, NSArray, or NSDictionary. NSNulls are not allowed. From the docs for writeToFile: