从核心数据和sqlite获取最大ID

Har*_*ish 5 core-data max ios

我有一个表用户,并在核心数据模型中有一堆列.其中一列是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;
Run Code Online (Sandbox Code Playgroud)

希望有人在此之前面对这个问题并修复它.

谢谢

Har*_*ish 3

感谢大家百忙之中抽空看问题。也谢谢各位的评论和解答。在解决从终端查看 sqlite 数据库的问题后,我注意到该表已损坏,并且它将所有垃圾值返回给我。问题其实很简单。这就是我为修复它所做的事情。

  1. 从 iPhone 模拟器中删除了该应用程序。
  2. 清洁溶液
  3. 重新编译程序。运行它,然后……它成功了。

只是为那些不知道如何从终端访问 sqlite 的人提供的开发人员提示。

  1. 找出你的 sqlite 的位置。通常将 /User/UserName/Library/Application Support/iPhone Simulator/6.1/xxxxxxxxxx/Documents cd 到此目录。

  2. 输入 sqlite3 命令

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

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

  5. 如果您想查看在 - 类型 .database 中运行的数据库

再次感谢大家。