如何在iOS应用程序中保存数据?

时间:2013-05-10 11:02:04

标签: ios save nsuserdefaults

我正在开发一个应用程序,用户在其中创建一个包含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!
     */
}

这是保存活动的正确方法吗?我现在如何检索我写的内容?

其次,如果我再次运行此代码,我会覆盖数据,还是创建新条目?

我想看看我每次都能做一个新的参赛作品。

此外,我想从我正在呈现的表中删除一个事件,所以我想看看删除是如何工作的。

我的“Note”对象如下所示:

@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

6 个答案:

答案 0 :(得分:2)

尝试

//Note.h 

#define kNoteCategory  @"Category"
#define kNoteName      @"Name"
#define kNoteEvent     @"Event"

@interface Note : NSObject

@property (nonatomic, copy) NSString *category;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *event;

- (id)initWithDictionary:(NSDictionary *)dictionary;

+ (NSArray *)savedNotes;
- (void)save;

// Note.m文件

- (id)initWithDictionary:(NSDictionary *)dictionary
{
    self = [super init];
    if (self)
    {
        self.category = dictionary[kNoteCategory];
        self.name = dictionary[kNoteName];
        self.event = dictionary[kNoteEvent];
    }

    return self;
}

+ (NSString *)userNotesDocumentPath
{
    NSString *documentsPath  = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"UserNotes.plist"];

    return documentsPath;

}

+ (NSArray *)savedNotes
{
    NSString *documentsPath = [self userNotesDocumentPath];
    NSArray *savedNotes = [NSArray arrayWithContentsOfFile:documentsPath];
    NSMutableArray *savedUserNotes = [@[] mutableCopy];
    for (NSDictionary *dict in savedNotes) {
        Note *note = [[Note alloc]initWithDictionary:dict];
        [savedUserNotes addObject:note];
    }

    return savedUserNotes;

}

- (NSDictionary *)userNoteDictionary
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    if (self.category) {
        dict[kNoteCategory] = self.category;
    }
    if (self.name) {
        dict[kNoteName] = self.name;
    }
    if (self.event) {
        dict[kNoteEvent] = self.event;
    }

    return dict;
}

- (void)saveUserNotesToPlist:(NSArray *)userNotes
{
    NSMutableArray *mutableUserNotes = [@[] mutableCopy];
    for (Note *note in userNotes) {
        NSDictionary *dict = [note userNoteDictionary];
        [mutableUserNotes addObject:dict];
    }
    NSString *documentsPath  = [Note userNotesDocumentPath];
    [mutableUserNotes writeToFile:documentsPath atomically:YES];
}

#pragma mark - Save

- (void)save
{
    NSMutableArray *savedNotes = [[Note savedNotes] mutableCopy];
    [savedNotes addObject:self];
    [self saveUserNotesToPlist:savedNotes];
}

保存记事
- (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;

    //Saves the note to plist
    [newNote save];

    //To get all saved notes
    NSArray *savedNotes = [Note savedNotes];
}

Source Code

答案 1 :(得分:0)

您可以使用NSKeyedUnArchiver来检索数据。如果您尝试在同一文件路径中写入

,它将重写

答案 2 :(得分:0)

看,我给你一般想法,你可以根据你的要求使用这个代码。

1)获取yourPlist.plist文件的“路径”:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"yourPlist.plist"]; 

2)将数据插入yourPlist:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:categoryField.text forKey:@"Category"];
[dict setValue:nameField.text forKey:@"Name"];
[dict setValue:eventField.text forKey:@"Event"];

NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:dict];

[arr writeToFile: path atomically:YES];

3)从yourPlist中检索数据:

NSMutableArray *savedStock = [[NSMutableArray alloc] initWithContentsOfFile: path];
for (NSDictionary *dict in savedStock) {
     NSLog(@"my Note : %@",dict);
}

答案 3 :(得分:0)

您可以使用核心数据保存所有数据,并在需要时将其删除。上面的代码总是创建Note类的新对象,所以每次有新数据,但是当你尝试使用相同的名称“Note”时。它总是覆盖旧数据。

答案 4 :(得分:0)

除了你可以使用Sqlite在你的应用程序本地保存数据之外,一切都是正确的。

这只是一个文件,但接受所有标准的sql语句。

这也是一种在本地保存数据的方法..

答案 5 :(得分:0)

通过NSUserDefaults保存数据我正在使用GVUserDefaults

用法

在GVUserDefaults上创建一个类别,在.h文件中添加一些属性,并在.m文件中创建@dynamic。

// .h
@interface GVUserDefaults (Properties)
@property (nonatomic, weak) NSString *userName;
@property (nonatomic, weak) NSNumber *userId;
@property (nonatomic) NSInteger integerValue;
@property (nonatomic) BOOL boolValue;
@property (nonatomic) float floatValue;
@end

// .m
@implementation GVUserDefaults (Properties)
@dynamic userName;
@dynamic userId;
@dynamic integerValue;
@dynamic boolValue;
@dynamic floatValue;
@end

现在,您只需使用[[NSUserDefaults standardUserDefaults] objectForKey:@"userName"]

,而不是使用[GVUserDefaults standardUserDefaults].userName

您甚至可以通过设置属性来保存默认值:

[GVUserDefaults standardUserDefaults].userName = @"myusername";