我有一个表用户并且在核心数据模型中有一堆列。其中一列是user_id,我试图获得最高的user_id并向其添加+ 1并将其传递给将要插入的下一个对象。我按照apple developer guide进行了操作并按照建议执行。这是我试图执行的代码。
问题是:我正在返回的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;
希望有人在此之前解决此问题并修复它。
谢谢
答案 0 :(得分:3)
谢谢大家看一下这个问题。还要感谢您的意见和解答。在搞清楚从终端查看sqlite数据库的问题之后,我注意到该表已损坏并且它将所有垃圾值返回给我。这个问题非常简单。这就是我为解决这个问题所做的工作。
仅为那些不了解从终端访问sqlite 的人提供开发者提示。
找出你的sqlite的位置。平时 / User / UserName / Library / Application Support / iPhone Simulator / 6.1 / xxxxxxxxxx / Documents cd到这个目录。
输入sqlite3命令
将“Application.sqlite”附加为db1
bam ..运行你的命令。
如果要查看在 - type .database
再次感谢大家。
答案 1 :(得分:1)
在我删除try / catch代码并在获取请求之后简化if语句后,此代码对我来说很好用:
if ([objects count] > 0) {
nextAccountId = [[[objects objectAtIndex:0] valueForKey:@"maxAccountId"] integerValue];
}
else {
nextAccountId = 0;
}
如果这没有解决,请确认您具有正确的初始化托管对象上下文(self._managedObjectContext
与self.managedObjectContext
,具体取决于您的定义)并且实体/属性名称是正确的。