magicalpanda / MagicalRecord

Super Awesome Easy Fetching for Core Data!
Other
10.8k stars 1.79k forks source link

MR_dateValueForKeyPath will nil a value that it can't parse #1188

Open gdunkle opened 8 years ago

gdunkle commented 8 years ago

My dates come down to the device via json as epoch milliseconds like this

  user =     {
        "_id" = 5451356be4b0c54793239842;
        "created" = 1414608235186;
}

I assumed this would not be a problem since I could just add an import function like the following

 func importCreated(value:AnyObject?)->Bool{
        if let epochMillis:String=value  as? String{
             let unixTimeStamp:NSTimeInterval = Double(epochMillis)! / 1000.0;
            self.created=NSDate.init(timeIntervalSince1970: unixTimeStamp);
            return true;
        }
        return false;
    }

The problem is the MR_dateValueForKeyPath method tries to convert the value and if it can't it just sets the value to nil.

I think the following change should be made to the MR_dateValueForKeyPath

- (NSDate *)MR_dateValueForKeyPath:(NSString *)keyPath fromObjectData:(id)objectData
{
    id value = [objectData valueForKeyPath:keyPath];
    if (![value isKindOfClass:[NSDate class]])
    {
        NSDate *convertedValue = nil;
        NSString *dateFormat;
        NSUInteger index = 0;
        do
        {
            NSString *dateFormatKey = kMagicalRecordImportCustomDateFormatKey;
            if (index)
            {
                dateFormatKey = [dateFormatKey stringByAppendingFormat:@".%tu", index];
            }
            index++;
            dateFormat = [[self userInfo] objectForKey:dateFormatKey];

            convertedValue = [value MR_dateWithFormat:dateFormat];

        } while (!convertedValue && dateFormat);
        //if the convertedValue is not equals to nil then update the value 
       //otherwise let the value flow through so that it can potentially be handled by an
      //import<AtrributeName> function
        if(convertedValue!=nil){
            value = convertedValue;
        }
    }
    return value;
}
Coeur commented 5 years ago

We can't have such change on (NSDate *)MR_dateValueForKeyPath:(NSString *)keyPath fromObjectData:(id)objectData: it must return an NSDate* or nil.

As for the importCreated, I believe it needs to be fixed in (void)MR_setAttribute:(NSAttributeDescription *)attributeInfo withValueFromObject:(id)objectData when the value is nil, by calling [objectData valueForKeyPath:keyPath]; and dealing with the raw data.