core data的primitive属性和transient属性

来源:互联网 发布:传奇清除所有玩家数据 编辑:程序博客网 时间:2024/05/17 05:54

1. -primitiveValueForKey:-setPrimitiveValue:forKey:这两个方法被core data使用,core data不仅仅需要知道你要修改一个属性,也需要知道你何时想访问他。

因此core data添加了-{will,did}AccessValueForKey:方法在getters中,添加了-{will,did}ChangeValueForKey:在setters方法中。

尽管如此,但是core data会处理潜在的modeled属性存储,你也同时需要处理。那么如果解决这个冲突呢?就允许声明@property and@dynamic 类型以方便自定义getter和setter方法来进行某些额外的处理。

2. 可以说这两个方法就是core data中针对modeled属性原始值raw value进行的set和get方法。

3. NSManagedObject对modeled对象禁用了自动的kvo变化通知功能。并且primitive accessor方法不回调用访问方法和更改通知方法。对于unmodeled属性,mac os x v10.4core data 也禁用了自动kvo;在mac os x10.5及以后,core data采用 NSObject的行为。

4. transient类型的属性不能作为fetchresultcontroller的sort key,否则读取会失败!


#import "APLEvent.h"


@interface APLEvent ()

@property (nonatomic) NSDate *primitiveTimeStamp;
@property (nonatomic) NSString *primitiveSectionIdentifier;

@end



@implementation APLEvent

@dynamic title, timeStamp, primitiveTimeStamp, sectionIdentifier, primitiveSectionIdentifier;

#pragma mark - Transient properties

- (NSString *)sectionIdentifier
{
    // Create and cache the section identifier on demand.

    [self willAccessValueForKey:@"sectionIdentifier"];
    NSString *tmp = [self primitiveSectionIdentifier];
    [self didAccessValueForKey:@"sectionIdentifier"];

    if (!tmp)
    {
        /*
         Sections are organized by month and year. Create the section identifier as a string representing the number (year * 1000) + month; this way they will be correctly ordered chronologically regardless of the actual name of the month.
         */
        NSCalendar *calendar = [NSCalendar currentCalendar];

        NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:[self timeStamp]];
        tmp = [NSString stringWithFormat:@"%d", ([components year] * 1000) + [components month]];
        [self setPrimitiveSectionIdentifier:tmp];
    }
    return tmp;
}


#pragma mark - Time stamp setter

- (void)setTimeStamp:(NSDate *)newDate
{
    // If the time stamp changes, the section identifier become invalid.
    [self willChangeValueForKey:@"timeStamp"];
    [self setPrimitiveTimeStamp:newDate];
    [self didChangeValueForKey:@"timeStamp"];

    [self setPrimitiveSectionIdentifier:nil];
}


#pragma mark - Key path dependencies

+ (NSSet *)keyPathsForValuesAffectingSectionIdentifier
{
    // If the value of timeStamp changes, the section identifier may change as well.
    return [NSSet setWithObject:@"timeStamp"];
}




0 0
原创粉丝点击