iOS / Objective-C:从NSManagedObject构建NSDictionary

时间:2018-07-09 19:45:11

标签: ios objective-c nsdictionary

我正在尝试从NSManagedObject构建NSDictionary。我的印象是,您可以使用以下方法执行此操作:NSMutableDictionary * myDict;     [myDict setObject:self.title forKey:@“ title”];      }

由于字典不能包含nil值,因此我首先测试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;

预先感谢您的任何建议。

1 个答案:

答案 0 :(得分:1)

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

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

第二,托管对象的任何属性都不会返回NSNull的值。您需要改为检查!= nil。有关null和nil之间差异的详细说明,请参见here