从核心数据获取最大ID&源码

时间:2013-05-09 01:44:29

标签: ios core-data max

我有一个表用户并且在核心数据模型中有一堆列。其中一列是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;

希望有人在此之前解决此问题并修复它。

谢谢

2 个答案:

答案 0 :(得分:3)

谢谢大家看一下这个问题。还要感谢您的意见和解答。在搞清楚从终端查看sqlite数据库的问题之后,我注意到该表已损坏并且它将所有垃圾值返回给我。这个问题非常简单。这就是我为解决这个问题所做的工作。

  1. 从iPhone模拟器中删除了应用程序。
  2. 清洁解决方案
  3. 重新编译程序。跑吧,bam ..它有效。
  4. 仅为那些不了解从终端访问sqlite 的人提供开发者提示。

    1. 找出你的sqlite的位置。平时 / User / UserName / Library / Application Support / iPhone Simulator / 6.1 / xxxxxxxxxx / Documents cd到这个目录。

    2. 输入sqlite3命令

    3. 将“Application.sqlite”附加为db1

    4. bam ..运行你的命令。

    5. 如果要查看在 - type .database

    6. 中运行的数据库

      再次感谢大家。

答案 1 :(得分:1)

在我删除try / catch代码并在获取请求之后简化if语句后,此代码对我来说很好用:

if ([objects count] > 0) {
    nextAccountId = [[[objects objectAtIndex:0] valueForKey:@"maxAccountId"] integerValue];
}
else {
    nextAccountId = 0;
}

如果这没有解决,请确认您具有正确的初始化托管对象上下文(self._managedObjectContextself.managedObjectContext,具体取决于您的定义)并且实体/属性名称是正确的。