从tableview存储光阵列的最佳实践

时间:2014-09-29 12:38:52

标签: ios objective-c arrays store

在我的应用程序中,我正在构建一个非常基本的邮件模板管理器,以便在使用相同主题/正文撰写多封电子邮件时为用户节省一些时间。

我有几个表格视图,用户可以从应用程序中提供的示例中选择模板,也可以添加/编辑自己的模板。

邮件模板有3个字段:

  • 模板名称(文本字段)
  • 电子邮件主题(文本字段)
  • 电子邮件正文(textview)
  • 模板是默认的(BOOL)

  • 将来我可能会实现附加文件(或对文件的引用)的能力。

现在应用程序中的示例都是硬编码的,但是在手机上存储用户添加模板的最佳方法是什么?

将模板设置为"默认"我想将它添加到userDefaults,是否正确? 要在手机上保存用户模板,我是否必须使用Core Data?或者有最简单的方法吗?

如果核心数据是可行的,那么任何人都可以链接到一个很好的教程吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

在我看来,个人核心数据对你所追求的东西来说是过度的。您可以将其添加到NSDictionary并将NSDictionary存储在NSUserDefaults中,就像您已经考虑过的那样。你可以有像

这样的东西
********WARNING THIS CODE IS UNTESTED********
// Probably best to rename this method something better but you get the idea
- (void)addTemplateWithSubject:(NSString *)subject Body:(NSString *)body forName:(NSString *)name shouldUseAsDefault:(BOOL)default
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    /* We want to retrieve ALL existing email template so we can check if 
     * our name already exists and if we have default already
     */
    NSMutableDictionary *existingEmailTemplates = [userDefaults dictionaryForKey:@"EmailTemplates"];

    // Now we have all our email templates lets see if one exists already
    if (![[existingEmailTemplates allKeys] containsObject:name]) {
        // If name doesn't exist lets start adding our new template
        NSMutableDictionary *emailTemplate = [[NSMutableDictionary alloc] init];
        [emailTemplate addObject:subject forKey:@"subject"];
        [emailTemplate addObject:body forKey:@"body"];
        [emailTemplate addObject:name forKey:@"name"];
        // and anything else you which to add here

        // Add our new template to the rest of the templates
        [existingEmailTemplates addObject:emailTemplate forKey:name];

        // Now store our existing templates back into our NSUserDefaults
        [userDefaults setObject:existingEmailTemplates forKey:@"EmailTemplates"];
        [userDefaults synchronize];
    } else {
        // Oops our name already exists
        // Just fill this alert view to warn the user that it already exists
        UIAlertView *templateAlreadyExistsAlert = [[UIAlertView alloc] initWithTitle:@"Warning!".....]; 
        /*
         * You may at this point want to offer the user to delete the old template 
         * in favor of this new one. That isn't covered here if you do want it covered
         * just ask and I'll update.
         */
    }
}