Core Data Transient Calculated Attributes

◇◆丶佛笑我妖孽 提交于 2019-12-04 11:50:01

问题


I have an entity that contains lastName and firstName attributes. For reasons beyond the scope of this question, I want a fullName attribute that gets calculated as a concatenation of firstName + space + lastName.

Because this is purely a calculated value, with no need for redo/undo or any other of the more sophisticated aspects of transient attributes (merging, etc.), my gut tells me to just override the getter method to return said calculated value. Reading suggests that, if I do this, my only concern would be whether it's KVO compliant, which I can address by using keyPathsForValuesAffectingVolume to ensure changes to firstName or lastName trigger notifications for anyone observing on fullName.

Am I missing anything? I'm checking because I'm a beginner to this environment.


回答1:


I'm also new to this, so I'm not completely sure about my answer, but as I understand it you are correct.

- (NSString *)fullName
{
    [self willAccessValueForKey:@"fullName"];
    NSString *tmp = [self primitiveFullName];
    [self didAccessValueForKey:@"fullName"];

    if (!tmp) {
        tmp = [NSString stringWithFormat:@"%@ %@", [self firstName], [self lastName]];
        [self setPrimitiveFullName:tmp];
    }
    return tmp;
}

- (void)setFirstName:(NSString *)aFirstName
{
    [self willChangeValueForKey:@"firstName"];
    [self setPrimitiveFirstName:aFirstName];
    [self didChangeValueForKey:@"firstName"];

    [self setPrimitiveFullName:nil];
}

- (void)setLastName:(NSString *)aLastName
{
    [self willChangeValueForKey:@"lastName"];
    [self setPrimitiveLastName:aLastName];
    [self didChangeValueForKey:@"lastName"];

    [self setPrimitiveFullName:nil];
}

+ (NSSet *)keyPathsForValuesAffectingFullName
{
    return [NSSet setWithObjects:@"firstName", @"lastName", nil];
}


来源:https://stackoverflow.com/questions/6034151/core-data-transient-calculated-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!