【问题标题】:IOS/Objective-C: Build NSDictionary from NSManagedObjectIOS/Objective-C:从 NSManagedObject 构建 NSDictionary
【发布时间】:2018-07-09 19:45:10
【问题描述】:

我正在尝试从 NSManagedObject 构建 NSDictionary。我的印象是你可以这样做: NSMutableDictionary *myDict; [myDict setObject:self.title forKey:@"title"]; }

因为字典不能保存 nil 值,所以我先测试 nil。但是,当我使用中断验证属性具有值时,当我构建字典时它是零。它使用断点显示为 nil,并将控制台记录为 NULL。希望有人确认以下是创建字典的有效方法,如果是,为什么字典会为零?

NSString *title = @"Test";
NSNumber *complete = @1;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *lasttouchedstr =[dateFormatter stringFromDate:[NSDate date]];

 NSMutableDictionary *myDict;
     if (self.title.length>=1) {
    [myDict setObject:self.title forKey:@"title"];
     }
    if (![self.complete isKindOfClass:[NSNull class]]) {
        [myDict setObject:self.complete forKey:@"complete"];
    }
    if (![self.lasttouched isKindOfClass:[NSNull class]]) {
        [myDict setObject:lasttouchedstr forKey:@"lasttouchedstr"];
    }
NSLog(@"myDict is:%@",myDict)//Logs as NULL
    return myDict;

提前感谢您的任何建议。

【问题讨论】:

    标签: ios objective-c nsdictionary


    【解决方案1】:

    NSMutableDictionary *myDict; 声明该值但不初始化它。你需要

    NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
    

    其次,托管对象的任何属性都不会返回NSNull 值。您需要改为检查 != nil。请参阅here 以获得对 null 和 nil 之间差异的很好的解释。

    【讨论】:

    • 太棒了!解决了我的问题。并感谢您的链接。我不断发现 NSNull 和 nil 令人困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 2023-03-29
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多