我有一个具有 3 个属性的实体:名字、姓氏和分数。我可以通过名字和姓氏搜索一个人的分数并将其显示在 UILabel 上(到目前为止很好)我的问题是我不知道如何用新值更新分数属性。在我用来执行搜索和显示旧值的代码下方。
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"Scorecard" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstname like %@ and lastname like %@", self.firstnameTextField.text, self.lastnameTextField.text];
[request setPredicate:predicate];
NSError *error;
NSArray *integer = [context executeFetchRequest:request error:&error];
if(integer.count <= 0){
self.displayLabel.text = @"No records found";
}
else {
NSNumber *score;
for (NSManagedObject *object in integer) {
score = [object valueForKey:@"score"];
int x = [score intValue];
// New Value is going to be the old value + 2
int y = x + 2;
//displays old value found
[self.displayLabel setText:[NSString stringWithFormat:@"old value %d",x]];
}
}
更新#1
我能够更新属性并保存它,但是我必须将我的新整数值转换为字符串,然后将其转换回整数。我不喜欢额外的步骤。如果有人有其他建议,请告诉我并感谢您的帮助。在更新的代码下方。
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"Scorecard" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstname like %@ and lastname like %@", self.firstnameTextField.text, self.lastnameTextField.text];
[request setPredicate:predicate];
NSError *error;
NSArray *integer = [context executeFetchRequest:request error:&error];
if(integer.count <= 0){
self.displayLabel.text = @"No records found";
}
else {
NSNumber *score;
for (NSManagedObject *object in integer) {
score = [object valueForKey:@"score"];
int x = [score intValue];
int y = x + 2;
NSString* z = [NSString stringWithFormat:@"%d",y];
[object setValue:[NSNumber numberWithInteger:[z integerValue]] forKey:@"score"];
[self.displayLabel setText:[NSString stringWithFormat:@"Value updated to %d",y]];
[context save:&error];
}
}
更新 2
感谢凯文的回答,我能够解决我的问题。我现在可以用另一个整数值替换我核心数据的属性中的整数值。下面我的代码终于工作了。
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"Scorecard" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstname like %@ and lastname like %@", self.firstnameTextField.text, self.lastnameTextField.text];
[request setPredicate:predicate];
NSError *error;
NSArray *integer = [context executeFetchRequest:request error:&error];
if(integer.count <= 0){
self.displayLabel.text = @"No records found";
}
else {
NSNumber *score;
for (NSManagedObject *object in integer) {
score = [object valueForKey:@"score"];
int x = [score intValue];
int y = x + 2;
[object setValue:[NSNumber numberWithInt:y] forKey:@"score"];
[self.displayLabel setText:[NSString stringWithFormat:@"Value updated to %d",y]];
[context save:&error];
}
}