1
votes

I am trying to build an NSDictionary from an NSManagedObject. I was under the impression that you could do this with: NSMutableDictionary *myDict; [myDict setObject:self.title forKey:@"title"]; }

Because a dictionary cannot hold nil values, I am testing for nil first. However, when I verify using a break that properties have values, when I build the dictionary it is nil. It shows as nil using a breakpoint and logs to console as NULL. Would appreciate someone confirming that the following is a valid way to create a dictionary and, if so, why the dictionary would be nil?

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;

Thanks in advance for any suggestions.

1

1 Answers

1
votes

NSMutableDictionary *myDict; declares the value but does not initialize it. You need

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

Secondly, managed objects will not be returning a value of NSNull for any of their attributes. You need to check for != nil instead. See here for a nice explanation of the differences between nulls and nils.