gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 04:42:02 25 4
gpt4 key购买 nike

我有一张用户表,在核心数据模型中有一堆列。其中一列是 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/Documentscd 到这个目录。

  2. 输入sqlite3命令

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

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

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

再次感谢大家。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com