【发布时间】:2013-05-05 01:15:24
【问题描述】:
我正在开发一个应用程序,用户创建一个包含 3 个字段的事件:
类别、名称、事件。 用户输入后,我有一个保存按钮,可以保存他的数据以供将来参考。然后当他再次打开应用程序时,数据将显示在表格视图中。
我究竟如何在 iOS 上“保存”数据?我知道 NSUserDefaults ,但我很确定这不是本示例的方式。
到目前为止我做了什么:
我创建了一个带有 Category 、 name 、 event 的“Note”类。
我的保存按钮的代码如下所示:
- (IBAction)save:(id)sender {
//creating a new "note" object
Note *newNote = [[Note alloc]init];
newNote.category = categoryField.text;
newNote.name = nameField.text;
newNote.event = eventField.text;
// do whatever you do to fill the object with data
NSData* data = [NSKeyedArchiver archivedDataWithRootObject:newNote];
/*
Now we create the path to the documents directory for your app
*/
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
/*
Here we append a unique filename for this object, in this case, 'Note'
*/
NSString* filePath = [documentsDirectory stringByAppendingString:@"Note"];
/*
Finally, let's write the data to our file
*/
[data writeToFile:filePath atomically:YES];
/*
We're done!
*/
}
这是保存活动的正确方法吗?我现在如何检索我写的内容?
其次,如果我再次运行此代码,我将覆盖数据,还是创建新条目?
我想看看如何每次都输入一个新条目。
我还想从我正在展示的表格中删除一个事件,所以我想看看删除是如何工作的。
我的“笔记”对象如下所示:
@interface Note : NSObject <NSCoding> {
NSString *category;
NSString *name;
NSString *event;
}
@property (nonatomic, copy) NSString *category;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *event;
@end
【问题讨论】:
-
要么学习核心数据,要么暂时坚持
NSUSerDefaults。 -
所以我存储的方式不对?
-
您有很多选择,保存为 plist、sqlite、核心数据。如果它很简单,你可以使用 plist。 NSUserDefaults 又是一个 plist,但不建议用于此目的。
-
你做的方式需要更多的劳动,这可能会导致更多的错误,应该是存储简单之类的最后一种方式。这些数据应该进入数据库
-
@LolaEnaMilo 坚持使用您自己的代码。它比答案提供的更好(假设您正确实施了 NSCoding 方法)。使用 NSCoding 没有错。你可以归档一个 NSMutableArray 来代替注释。
标签: ios save nsuserdefaults