【问题标题】:How to read date from CoreData saved as NSString?如何从保存为 NSString 的 CoreData 中读取日期?
【发布时间】:2013-06-11 03:35:26
【问题描述】:

我有包含属性 dateUpdated 的 CoreData 实体(类型为“2013-06-27”的NSString)。

当我想读取这个值时,它返回 nil

Recipes *oldRecipe;
oldRecipe = [self getRecipeWithCode:i];
NSDateFormatter *dtFormatter = [[NSDateFormatter alloc] init];
[dtFormatter setDateFormat:@"yyyy-MM-dd"];

NSString *oDate = oldRecipe.dateUpdated; 
//after this oDate is nil
NSDate *oldDate = [dtFormatter dateFromString:oDate];

我已经使用 SQL 管理器检查了实体中的值存在。

我怎样才能正确地做到这一点?

【问题讨论】:

  • 要么'[self getRecipeWithCode:i];'在您的核心数据数据库中返回niloldRecipe.dateUpdatednil。使用NSLog() 确定是哪个,然后从那里追踪问题。
  • oldRecipe.dateUpdated 返回nil 的一个原因可能是创建oldRecipe 的托管对象上下文不再存在。您是否使用多个上下文?
  • @MartinR 是的,我正在使用多个上下文,但 [self getRecipeWithCode:i] 返回非零数据
  • @Romowski:托管对象只能存在于创建它的上下文中。如果上下文被释放,则oldRecipe 将不是nil,但访问属性将始终返回 nil .
  • @MartinR 谢谢!!!使用主上下文解决了问题!!!您可以发布您的第二个答案,就像我的问题的答案一样,我会接受)

标签: ios core-data nsdate


【解决方案1】:

正如讨论中证明的那样,oldRecipe 对象是在 getRecipeWithCode 使用临时托管对象上下文的方法。

托管对象只能存在于创建它的上下文中。如果释放上下文,则oldRecipe 将不会为 nil,但访问其属性将始终返回 nil。

【讨论】:

    猜你喜欢
    • 2018-06-22
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    相关资源
    最近更新 更多