计算核心数据属性的最大值 - NSCFNumber 错误 [英] Calculating the max value for a core data attribute - NSCFNumber error

查看:10
本文介绍了计算核心数据属性的最大值 - NSCFNumber 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找出核心数据实体的属性的最大值.

我仍然牢牢掌握 Cocoa 学习曲线,这是一个我用来学习的简单测试应用.

该应用程序从文本文件中导入财富并在屏幕上显示一个表格.导入在单独的后台线程中完成.

我在网上找到了这个代码,我试图让它工作:

- (double)getMaxID{NSLog(@"in getMaxID");//调试//使用新的 moc 和原来的persistentStoreCoordinator 来保证线程安全NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];[moc setPersistentStoreCoordinator:[[自我委托]persistentStoreCoordinator]];//创建获取NSFetchRequest *fetch = [[NSFetchRequest alloc] init];[获取 setEntity:[NSEntityDescription entityForName:@"Fortune" inManagedObjectContext:moc]];[获取 setResultType:NSDictionaryResultType];//最大 ID 的表达式NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"id"];NSExpression *minExpression = [NSExpression expressionForFunction:@"max:" 参数:[NSArray arrayWithObject:keyPathExpression]];NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];[表达式描述集名称:@"maxID"];[表达式描述 setExpression:minExpression];[表达式描述 setExpressionResultType:NSDoubleAttributeType];[fetch setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];//执行提取.加倍 ID = 0;NSError *error = nil;NSArray *objects = nil;objects = [moc executeFetchRequest:fetch error:&error];//在这里崩溃if (objects && ([objects count] > 0)){NSLog(@"查询成功");//调试theID = [((NSNumber *)[[objects objectAtIndex:0] valueForKey:@"maxID"]) doubleValue];}别的{NSLog(@"设置ID的默认值");//调试ID = 0;}返回(ID);}

我的实体名为Fortune",属性名为id"(双精度型).

当代码运行时,它会在执行 fetch 请求时崩溃.控制台显示:

<前>2009-12-18 00:53:42.777 FortunesHelperMVC[4027:1703] -[NSCFNumber count]:无法识别的选择器发送到实例 0x1004d7b102009-12-18 00:53:42.778 FortunesHelperMVC [4027:1703] 引发了一个未捕获的异常2009-12-18 00:53:42.778 FortunesHelperMVC[4027:1703] -[NSCFNumber count]:无法识别的选择器发送到实例 0x1004d7b102009-12-18 00:53:42.779 FortunesHelperMVC[4027:1703] *** 由于未捕获的异常NSInvalidArgumentException"而终止应用程序,原因:-[NSCFNumber count]:无法识别的选择器发送到实例 0x1004d7b10"*** 第一次抛出时调用堆栈:(0 核心基金会 0x00007fff83ed9444 __exceptionPreprocess + 1801 libobjc.A.dylib 0x00007fff85fbb0f3 objc_exception_throw + 452 CoreFoundation 0x00007fff83f321c0 +[NSObject(NSObject)doesNotRecognizeSelector:] + 03 核心基金会 0x00007fff83eac08f ___转发___ + 7514 核心基金会 0x00007fff83ea81d8 _CF_forwarding_prep_0 + 2325 基础 0x00007fff88a5609e +[_NSPredicateUtilities max:] + 466 基础 0x00007fff8893ce72 -[NSFunctionExpression expressionValueWithObject:context:] + 5307 核心数据 0x00007fff8613b5b1 -[NSMappedObjectStore executeFetchRequest:withContext:] + 20818 核心数据 0x00007fff8613ad10 -[NSMappedObjectStore executeRequest:withContext:] + 809 核心数据 0x00007fff86108900 -[NSPersistentStoreCoordinator(_NSInternalMethods) executeRequest:withContext:] + 68810 核心数据 0x00007fff8610621b -[NSManagedObjectContext executeFetchRequest:error:] + 26711 FortunesHelperMVC 0x0000000100001d9d -[ImportOperation getMaxID] + 57212 FortunesHelperMVC 0x0000000100001f95 -[ImportOperation main] + 33013 基金会 0x00007fff888f406d -[__NSOperationInternal start] + 68114 基础 0x00007fff888f3d23 ____startOperations_block_invoke_2 + 9915 libSystem.B.dylib 0x00007fff86a98ce8 _dispatch_call_block_and_release + 1516 libSystem.B.dylib 0x00007fff86a77279 _dispatch_worker_thread2 + 23117 libSystem.B.dylib 0x00007fff86a76bb8 _pthread_wqthread + 35318 libSystem.B.dylib 0x00007fff86a76a55 start_wqthread + 13)抛出NSException"的实例后调用终止

任何想法为什么这不起作用?我在谷歌上搜索了很多次之后被难住了.

谢谢

达伦.

解决方案

我不得不解决一个类似的问题,并通过以下方式处理它:

  • 查询实体
  • 按所需属性排序
  • 将获取结果限制为 1

代码如下.我正在查询一个名为entityName"的实体并检索属性sequenceId"的最大值.

 NSFetchRequest *request = [[NSFetchRequest alloc] init];NSEntityDescription *res = [NSEntityDescription entityForName:@"entityName" inManagedObjectContext:managedObjectContext];[请求 setEntity:res];NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sequenceId" 升序:否];NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];[请求 setSortDescriptors:sortDescriptors];[sortDescriptors 发布];[sortDescriptor 发布];[请求 setFetchLimit:1];NSError *error = nil;NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];[请求释放];如果(结果 == 零){NSLog(@"获取结果出错:%@",error);}NSInteger 最大值 = 0;如果(结果数== 1){结果 *result = (Result*)[results objectAtIndex:0];maximumValue = [result.sequenceId integerValue];}

I need to find out the maximum value of an attribute of a core data entity.

I'm still firmly in the Cocoa learning curve, and this is a simple test app that I'm using to learn.

The app imports fortunes from a text file and displays a table on the screen. The imports are done in a separate, background thread.

I found this code online, which I have attempted to get working:

- (double)getMaxID  
{  
    NSLog(@"in getMaxID");  // debug  

    // Use a new moc with the original persistentStoreCoordinator to ensure thread safety  
    NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];  
    [moc setPersistentStoreCoordinator:[[self delegate] persistentStoreCoordinator]];  

    // Create fetch  
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];  
    [fetch setEntity:[NSEntityDescription entityForName:@"Fortune"   inManagedObjectContext:moc]];  
    [fetch setResultType:NSDictionaryResultType];  

    // Expression for Max ID  
    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"id"];  
    NSExpression *minExpression = [NSExpression expressionForFunction:@"max:" arguments:  [NSArray arrayWithObject:keyPathExpression]];  
    NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];  
    [expressionDescription setName:@"maxID"];  
    [expressionDescription setExpression:minExpression];  
    [expressionDescription setExpressionResultType:NSDoubleAttributeType];  
    [fetch setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];  

    // Execute the fetch.  
    double theID = 0;  
    NSError *error = nil;  
    NSArray *objects = nil;  
    objects = [moc executeFetchRequest:fetch error:&error];  // crashes here  

    if (objects && ([objects count] > 0))  
    {  
        NSLog(@"query successful"); // debug  
        theID = [((NSNumber *)[[objects objectAtIndex:0] valueForKey:@"maxID"]) doubleValue];  
    }  
    else  
    {  
        NSLog(@"Setting default value for theID"); // debug  
        theID = 0;  
    }  

    return(theID);  
} 

My entity is called "Fortune" and the attribute is called "id" (a Double).

When the code runs it crashes when the fetch request is executed. The console shows this:

2009-12-18 00:53:42.777 FortunesHelperMVC[4027:1703] -[NSCFNumber count]: unrecognized selector sent to instance 0x1004d7b10  
2009-12-18 00:53:42.778 FortunesHelperMVC[4027:1703] An uncaught exception was raised  
2009-12-18 00:53:42.778 FortunesHelperMVC[4027:1703] -[NSCFNumber count]: unrecognized selector sent to instance 0x1004d7b10  
2009-12-18 00:53:42.779 FortunesHelperMVC[4027:1703] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFNumber count]: unrecognized selector sent to instance 0x1004d7b10'  
*** Call stack at first throw:  
(
0 CoreFoundation 0x00007fff83ed9444 __exceptionPreprocess + 180  
1 libobjc.A.dylib 0x00007fff85fbb0f3 objc_exception_throw + 45  
2 CoreFoundation 0x00007fff83f321c0 +[NSObject(NSObject) doesNotRecognizeSelector:] + 0  
3 CoreFoundation 0x00007fff83eac08f ___forwarding___ + 751  
4 CoreFoundation 0x00007fff83ea81d8 _CF_forwarding_prep_0 + 232  
5 Foundation 0x00007fff88a5609e +[_NSPredicateUtilities max:] + 46  
6 Foundation 0x00007fff8893ce72 -[NSFunctionExpression expressionValueWithObject:context:] + 530  
7 CoreData 0x00007fff8613b5b1 -[NSMappedObjectStore executeFetchRequest:withContext:] + 2081  
8 CoreData 0x00007fff8613ad10 -[NSMappedObjectStore executeRequest:withContext:] + 80  
9 CoreData 0x00007fff86108900 -[NSPersistentStoreCoordinator(_NSInternalMethods) executeRequest:withContext:] + 688  
10 CoreData 0x00007fff8610621b -[NSManagedObjectContext executeFetchRequest:error:] + 267  
11 FortunesHelperMVC 0x0000000100001d9d -[ImportOperation getMaxID] + 572  
12 FortunesHelperMVC 0x0000000100001f95 -[ImportOperation main] + 330  
13 Foundation 0x00007fff888f406d -[__NSOperationInternal start] + 681  
14 Foundation 0x00007fff888f3d23 ____startOperations_block_invoke_2 + 99  
15 libSystem.B.dylib 0x00007fff86a98ce8 _dispatch_call_block_and_release + 15  
16 libSystem.B.dylib 0x00007fff86a77279 _dispatch_worker_thread2 + 231  
17 libSystem.B.dylib 0x00007fff86a76bb8 _pthread_wqthread + 353  
18 libSystem.B.dylib 0x00007fff86a76a55 start_wqthread + 13  
)  
terminate called after throwing an instance of 'NSException'  

Any ideas why this isn't working? I'm stumped after a lot of Googling.

Thanks

Darren.

解决方案

I had to solve a similar problem and approached it slightly differently by:

  • querying the entity
  • ordering by the attribute you want
  • limit the fetch results to 1

The code for this is below. I am querying an entity called 'entityName' and retrieving the max value for the attribute 'sequenceId'.

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *res = [NSEntityDescription entityForName:@"entityName" inManagedObjectContext:managedObjectContext];
[request setEntity:res];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sequenceId" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];

[request setFetchLimit:1];

NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
[request release];
if (results == nil) {
    NSLog(@"error fetching the results: %@",error);
}

NSInteger maximumValue = 0;
if (results.count == 1) {
    Result *result = (Result*)[results objectAtIndex:0];
    maximumValue =  [result.sequenceId integerValue];
}

这篇关于计算核心数据属性的最大值 - NSCFNumber 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆