有人能帮助我理解这个例子中,原始的访问者:我不明白什么是自动设置的,这些方法的顺序:原始存取
1.after一个人创建的,是willSave
第一种方法叫做? (我猜是这样,因为我们创建insertNewObjectForEntityForName
后,一个人叫)
2.in RootViewController的(代码的第二块),就可以调用的eyeColor
,吸气用:person.eyeColor
:
一)eyeColor
,我们称之为:[self eyeColorData]
,
b)但setPrimitiveEyeColorData
为willSave
,仅如果primitiveEyeColor
存在访问,
C)但setPrimitiveEyeColor
是eyeColor
,只称为如果[self eyeColorData]
存在。所以,我对这段代码有点困惑,有人可以帮我吗?
这里的代码约eyeColor
和eyeColorData
:
@dynamic eyeColorData;
@dynamic eyeColor;
@interface AWPerson (PrimitiveAccessors)
- (UIColor *)primitiveEyeColor;
- (void)setPrimitiveEyeColor:(UIColor *)value;
- (NSData *)primitiveEyeColorData;
- (void)setPrimitiveEyeColorData:(NSData *)value;
@end
+ (id)personInManagedObjectContext:(NSManagedObjectContext *)moc {
return [NSEntityDescription
insertNewObjectForEntityForName:@"Person"
inManagedObjectContext:moc];
}
+ (id)randomPersonInManagedObjectContext:(NSManagedObjectContext *)moc {
AWPerson *randomPerson = [self personInManagedObjectContext:moc];
//...
randomPerson.eyeColor = [self randomColor]; //setter eyeColor
return randomPerson;
}
+ (UIColor *)randomColor {
static NSArray *colorsArray = nil;
if(!colorsArray) {
colorsArray = [[NSArray alloc] initWithObjects:
[UIColor lightGrayColor],
[UIColor blueColor],
[UIColor greenColor], nil];
}
int randomIndex = arc4random() % [colorsArray count];
return [colorsArray objectAtIndex:randomIndex];
}
- (void)willSave {
UIColor *color = [self primitiveEyeColor];
if(color) {
[self setPrimitiveEyeColorData:
[NSKeyedArchiver archivedDataWithRootObject:color]];
} else {
[self setPrimitiveEyeColorData:nil];
}
[super willSave];
}
- (UIColor *)eyeColor {
[self willAccessValueForKey:@"eyeColor"];
UIColor *tmpValue = [self primitiveEyeColor];
[self didAccessValueForKey:@"eyeColor"];
if(tmpValue) return tmpValue;
NSData *colorData = [self eyeColorData];
if(!colorData) return nil;
tmpValue = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
[self setPrimitiveEyeColor:tmpValue];
return tmpValue;
}
在RootViewController的:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
AWPerson *person = [[self fetchedResultsController] objectAtIndexPath:indexPath];
[cell setBackgroundColor:person.eyeColor];
}
感谢
感谢lnafziger,a)'randomPerson.eyeColor = [self randomColor]'中的颜色可以通过'[self primitiveEyeColor]'(in'willSave')访问? b)所以如果'[self primitiveEyeColor]!= nil':在'eyeColor'中,行:'if(tmpValue)return tmpValue;'因此应该总是真的......我们何时可以取消存档'eyeColorData'如果'UIColor * tmpValue = [self primitiveEyeColor]'总是在' - (UIColor *)eyeColor'中返回?再次感谢 – Paul 2012-04-06 00:01:27
我更新了我的答案以解决这些问题,以便我有更多空间。 :) – lnafziger 2012-04-06 03:41:41
谢谢!关于你的n°3:在我们保存物体后,我们在哪里设置eyeColor为零? – Paul 2012-04-06 11:09:55