gpt4 book ai didi

objective-c - 获取实体中某个值的最大值

转载 作者:行者123 更新时间:2023-12-03 16:44:28 24 4
gpt4 key购买 nike

我正在尝试获取核心数据中实体中属性的最大值。苹果有一个很好的例子here如何做到这一点;但是,它对我不起作用。我的 moc 中有 10 个对象,下面的代码总是返回一个大小为 0 的数组。谁能告诉我我做错了什么?谢谢!

  NSManagedObjectContext* moc = [self managedObjectContext];

// set the idx to the maximum value
NSFetchRequest* request = [[NSFetchRequest alloc] init];
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Transaction"
inManagedObjectContext:moc];
[request setEntity:entity];

// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];

// Create an expression for the key path.
NSExpression* keyPathExpression = [NSExpression expressionForKeyPath:@"idx"];

// Create an expression to represent the minimum value at the key path 'creationDate'
NSExpression* maxExpression = [NSExpression expressionForFunction:@"max:"
arguments:[NSArray arrayWithObject: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:@"maxIdx"];
[expressionDescription setExpression:maxExpression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];

// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

// Execute the fetch.
NSError* error = nil;
NSArray* objects = [moc executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
int newIdx = [[[objects objectAtIndex:0] valueForKey:@"maxIdx"] intValue] + 1;
[self setPrimitiveIdx:[NSNumber numberWithInt:newIdx]];
} else {
[self setPrimitiveIdx:[NSNumber numberWithInt:1]];
}
}

最佳答案

您的代码对我来说看起来不错,因此请检查以下内容

  1. 您的商店中实际上有 Transaction 对象。只需从相同的上下文中进行正常的获取即可。

  2. 您可以在设置上下文之前执行此操作吗?

  3. 检查是否有任何错误 - 只需记录 [error localDescription]

  4. NSInteger32AttributeType 适合 idx 吗?

  5. idx 拼写正确吗?是交易吗?意思是,它们与您的模型匹配。

PS:结果并不重要,但希望您能从代码示例中获得版本

关于objective-c - 获取实体中某个值的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5134195/

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