访问核心数据对象时出现NSInvalidArgumentException

时间:2015-03-31 07:37:54

标签: core-data ios5.1

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Contacts length]:

我从核心数据中提取图像,显然图像的格式是BYTE,所以我将其转换为图像。我正在使用以下代码:

NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Contacts"
                               inManagedObjectContext:context]];

NSError * error = nil;
NSArray * objects = [context executeFetchRequest:request error:&error];
NSData *data1= objects[0];

UIImage *image2 = [[UIImage alloc]initWithData:data1];

怎么办?

2 个答案:

答案 0 :(得分:1)

[context executeFetchRequest:request error:&error];返回一个实例为NSManagedObject的数组或NSManagedObject的子类。您告诉编译器该数组包含NSData的实例,但实际情况并非如此。因此,未知的选择器方法。

如果我们假设您将图像数据保存在名为imageData的属性中,那么您的代码将如下所示:

NSArray * objects = [context executeFetchRequest:request error:&error];
NSAssert(objects, @"Can't fetch: %@", error);
if ([objects count] > 0) {
    NSManagedObject *object = objects[0];
    NSData *data = [object valueForKey:@"imageData"];
}

答案 1 :(得分:0)

您可以使用以下

NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity1 = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];
[fetchRequest setEntity:entity1];
NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
 NSData * dataBytes = [[array objectAtIndex:0] imgPng];
image = [UIImage imageWithData:dataBytes];