我有一个 coredata 项目,我正在尝试以编程方式更新一个数字。我正在从 CoreData 中检索对象,然后将其存储到一个数组中。
然后,我遍历该数组以查看当前用户的 IP 是否存在于数据库中,并尝试更新该特定数组的访问次数。
问题是,它正在更新所有对象,而不仅仅是循环数组中的当前对象。
首先,我从核心数据中获取信息,如下所示:
- (void)fetchRecords {
// Define our table/entity to use
NSEntityDescription *entity = [NSEntityDescription entityForName:@"IPAddr" inManagedObjectContext:managedObjectContext];
// Setup the fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
// Define how we will sort the records
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"ipDate" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[request setSortDescriptors:sortDescriptors];
// Fetch the records and handle an error
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (!mutableFetchResults) {
// Handle the error.
// This is a serious error and should advise the user to restart the application
}
// Save our fetched data to an array
[self setIpArray: mutableFetchResults];
}
现在,我正在尝试查找当前用户 IP 是否存在于获取的结果中,如果存在,则更新访问次数:
// see if the ip is present and update if necessary
-(void)ipPresent {
NSString * theCurrentIP = [self getGlobalIPAddress];
for (IPAddr *allips in ipArray)
{
if ([allips.ipNum isEqualToString:theCurrentIP]) {
NSLog(@"The IP %@ was found.", theCurrentIP);
// update the ip
NSError *error = nil;
NSNumber *ipToUpdate = allips.ipAccess;
NSNumber *addIpAccess = [[NSNumber alloc] initWithInt:1];
NSNumber *updateIpAddress = [NSNumber numberWithFloat:([ipToUpdate floatValue] + [addIpAccess floatValue])];
[self.ipArray setValue:updateIpAddress forKey:@"ipAccess"];
if ([self.managedObjectContext save:&error]) { // write to database
NSLog(@"The IP Was Updated from %@ to %@", ipToUpdate, updateIpAddress);
} else if (![self.managedObjectContext save:&error]) {
NSLog(@"failed with error: %@", error);
}
break;
} else {
NSLog(@"The IP %@ was NOT found.", theCurrentIP);
}
}
}
我很确定问题出在这一行:
[self.ipArray setValue:updateIpAddress forKey:@"ipAccess"];
同样,它正在更新所有实体,而不仅仅是当前循环中的实体。