【问题标题】:How to save data , in an iOS application?如何在 iOS 应用程序中保存数据?
【发布时间】: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


【解决方案1】:

试试

//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

【讨论】:

  • 我在 note.m 类中遇到了一些错误。你确定是完整的?一开始不应该有@ implementation @ end 什么的?我在文件末尾找到了一个 @end 丢失,在文件的开头也是一个奇怪的错误..
  • @LolaEnaMilo 您遇到的错误是什么。我故意没有包含琐碎的代码。
  • 好的,我修好了。我现在正在测试它。我稍后会提供反馈。如果它有效,问题是你的.. 同时提供一些关于如何从数组中删除字典的代码。
  • @LolaEnaMilo 我已将我之前制作的源代码放在我的答案中。
  • 我运行了代码。事实是我有点困惑。 NSArray *savedNotes 里面到底有什么?我想是一个带有字典的数组吗?如果是,我如何打印它以查看里面的值?另外,我如何在此数组中引用字典(即注释)?我试图打印数组,但我只打印了类别。没有其他的。我希望有一本包含所有值的字典。但至少它不会覆盖。每次它也会给我打印上一个类别
【解决方案2】:

您可以使用 NSKeyedUnArchiver 来检索数据。如果您尝试写入相同的文件路径,它将覆盖写入

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      除了您可以使用 Sqlite 将数据与您的应用程序一起保存在本地之外,其他所有内容都是正确的。

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

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

      【讨论】:

      • 我现在正在看。看起来非常非常有趣。
      【解决方案5】:

      为了通过 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
      

      现在,您可以简单地使用[GVUserDefaults standardUserDefaults].userName,而不是使用[[NSUserDefaults standardUserDefaults] objectForKey:@"userName"]

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

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

      【讨论】:

        【解决方案6】:

        你看,我给你的总体思路,你可以根据你的要求使用这个代码。

        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);
        }
        

        【讨论】:

        • 非常感谢先生。你能告诉我如何保存像“Note”这样的对象(见更新的问题)以及如何检索它。还有如何不覆盖数据。
        • @LolaEnaMilo :再次检查我的代码。
        • 我会接受你的回答,如果你能告诉我笔记被一个接一个地保存而不被覆盖的部分在哪里。我看不出如何使用此代码检索 5 个不同的笔记。 objectAtIndex:number 是 Note 的位置吗?所以如果我放在那里 1 , 2 , 3 我得到下一个笔记?如果是,我怎么知道保存在那里的笔记的数量,以便我可以正确检索它们?
        • @LolaEnaMilo :[arr addObject:dict]; 是将“添加”新注释到 Array 的部分,而不是“覆盖”。每个NSMutableDictionary 都是您的“单一”笔记。
        • 所以如果我现在理解得很好以检索所有笔记,我唯一要做的就是查看 newDict 的大小,然后 newDict = [savedStock objectAtIndex:0];在这里我使用 1 2 3 4 直到 size-1 来获取所有的音符?还有这一行: NSString *documentsDirectory = [paths objectAtIndex:0];我总是这样留下它还是我必须为每个新音符制作 1 2 3 ?最后,如果你能提供我注意的删除方法,请。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多