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

标签 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;

希望之前有人遇到过这个问题并解决了它。

谢谢

最佳答案

谢谢大家看问题。也感谢您的评论和回答。在找出从终端查看 sqlite 数据库的问题后,我注意到该表已损坏,并且它正在将所有垃圾值还给我。问题其实很简单。这就是我为修复它所做的工作。

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

对于那些不知道从终端访问 sqlite 的人来说,这只是一个开发人员提示。

  1. 确定您的 sqlite 的位置。通常 /User/用户名/Library/Application Support/iPhone Simulator/6.1/xxxxxxxxxx/Documents cd 到这个目录。

  2. 输入sqlite3命令

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

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

  5. 如果您想查看其中运行的数据库 - 输入 .database

再次感谢大家。

关于ios - 从核心数据和 sqlite 获取最大 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16453041/

相关文章:

sql - 如何使用 SQL 从每个组中获得最高得分球员?

r - 使用Zoo包查找确定的数据组的最大值

ios - "self"在 Swift 中有什么用?

ios - iOS 9.3 中 Swift 4.0 的未知崩溃

ios - 核心数据精确存储 NSDecimalNumber

ios - 核心数据,获取某个 bool 值属性的总和

c# - ElasticSearch(C#Nest)中的多个最大/最小聚合

html - CSS3 奇怪的行为边框 Safari iOS 和 iPad

ios - 通过在 Swift 中按下按钮触发本地通知权限对话框

iphone - tabBar 应用程序在 iPhone 设备上启动非常缓慢