问题描述
我有一个包含lastName和firstName属性的实体。由于超出了这个问题的范围,我想要一个fullName属性,它被计算为firstName + space + lastName的并置。
因为这只是一个计算值,没有必要重做/撤消或任何其他更复杂的方面的瞬态属性(合并等),我的肠告诉我,只是重写getter方法返回所述计算值。阅读建议,如果我这样做,我唯一的关注是,它是KVO兼容,我可以通过使用keyPathsForValuesAffectingVolume来确保更改firstName或lastName触发通知任何观察fullName。
我缺少什么吗?
Wayne
我也是新的,所以我不完全确定我的答案,但是我明白你是正确的。
- (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]
}
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 newbie to this environment.
Wayne
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];
}
这篇关于核心数据瞬态计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!