Why is an NSDate in a Core Data managed Object converted to NSTimeInterval?

后端 未结 3 408
别跟我提以往
别跟我提以往 2020-12-09 16:48

I have an object with a property with a Date type defined in my xcdatamodeld object. Why has it generated the NSManagedObject class with a NSTimeInterval? And how do I set a

3条回答
  •  渐次进展
    2020-12-09 17:07

    If you want to have mixed entities that uses both scalar and non-scalar property representations such as int32_t for integer or boolean properties but NSDate* for date properties, you need to manually edit the generated managed object .h file.

    Therefore I usually start with creating managed object classes by checking the option Use scalar properties for primitive data types (as I have more integer and boolean properties than dates). Then I edit the created header file as follows:

    MYEntity.h

    @interface MYEntity : NSManagedObject
    @property (nonatomic) int32_t index;
    @property (nonatomic) NSTimeInterval date;
    @end
    

    then becomes:

    @interface MYEntity : NSManagedObject
    @property (nonatomic) int32_t index;
    @property (nonatomic, retain) NSDate * date;
    @end
    

    If you are of the kind who doesn't like to manually edit this file, you can also choose to add a convenience property using a category that allows for accessing the scalar property as if it would be an object.

    MYEntity+Convenience.h:

    @interface MYEntity (Convenience)
    @property (nonatomic, readwrite) NSDate *theDate
    @end
    

    MYEntity+Convenience.h:

    @implementation MYEntity (Convenience)
    
    - (NSDate *)theDate {
        return [NSDate dateWithTimeIntervalSinceReferenceDate:self.date];
    }
    
    - (void)setTheDate:(NSDate *)theDate {
        self.date = [theDate timeIntervalSinceReferenceDate]
    }
    
    @end
    

    To make the code more readable in this example I would name the original property dateTimeInterval in the data model designer and the convenience property with its desired name: date.

    The second approach obviously also works vice versa. You can export your entities with non-scalar properties and then provide a convenience scalar property whose getter and setter accesses the original non-scalar property.

提交回复
热议问题