我有一个表用户,并且在核心数据模型中有一堆列。其中一列是 user_id ,我正在尝试获取最高的 user_id 并为其添加 + 1 并将其传递给将插入的下一个对象。我遵循苹果开发者指南并按照建议实施。这是我要执行的代码。
问题是:我正在返回的 account_id 值被设置为一些奇怪的数字,甚至在数据库中都不存在。
"account_id" = 139784529; 它应该是 1,因为我只保存了核心数据。
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Users" inManagedObjectContext:self._managedObjectContext];
[request setEntity:entity];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"account_id"];
// Create an expression to represent the function you want to apply
NSExpression *expression = [NSExpression expressionForFunction:@"max:"
arguments:@[keyPathExpression]];
// Create an expression description using the minExpression and returning a date.
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
// The name is the key that will be used in the dictionary for the return value.
[expressionDescription setName:@"maxAccountId"];
[expressionDescription setExpression:expression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType]; // For example, NSDateAttributeType
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:@[expressionDescription]];
// Execute the fetch.
NSError *error;
NSArray *objects = [self._managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
nextAccountId = [[[objects objectAtIndex:0] valueForKey:@"maxAccountId"] integerValue];
}
}
}
@catch (NSException *exception) {
NSLog(@"%@",[exception reason]);
}
return nextAccountId + 1;
希望有人以前遇到过这个问题并解决了它。
谢谢