保存和检索UIImage在CoreData [英] Save and Retrieve of an UIImage on CoreData

查看:182
本文介绍了保存和检索UIImage在CoreData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程式中,我尝试储存和检索核心资料中的图片。我可以保存一个图像成功后UIimage到NSData中,但是当我想获得一个图像作为NSData它显示输出如下所示,



case 1 :尝试从DB显示为字符串。

 < Event:0x5b5d610& (entity:Event; id:0x5b5ce30< x-coredata:// F51BBF1D-6484-4EB6-8583-147E23D9FF7B / Event / p1> ;; data:< fault>)
/ pre>

情况2:尝试显示为数据



  [Event length]:无法识别的选择器发送到实例0x5b3a9c0 
2010-07-28 19:11:59.610 IMG_REF [10787:207] ***由于未捕获异常而终止应用程序NSInvalidArgumentException,原因:长度]:无法识别的选择器发送到实例0x5b3a9c0'

我的代码,

 保存:

NSManagedObjectContext * context = [self managedObjectContext];

newsObj = [NSEntityDescription insertNewObjectForEntityForName:@EventinManagedObjectContext:context];

NSURL * url = [NSURL URLWithString:@http://www.cimgf.com/images/photo.PNG];

NSData * data = [[NSData alloc] initWithContentsOfURL:url];

uiImage = [UIImage imageWithData:data];

NSData * imageData = UIImagePNGRepresentation(uiImage);

[newsObj setValue:imageData forKey:@imgPng];

NSError * error;

@try {

if(managedObjectContext!= nil){

if(![managedObjectContext save:& error]){

NSLog(@未解析的错误%@,%@,错误,[错误userInfo]);

NSString * infoString = [NSString stringWithFormat:@请检查您的连接,然后重试。

UIAlertView * infoAlert = [[UIAlertView alloc] initWithTitle:@数据库连接错误消息:infoString委托:self cancelButtonTitle:@OKotherButtonTitles:nil];

[infoAlert show];

[infoAlert release];
}
}

} @catch(NSException * exception){

NSLog(@within exception);
}

检索

  NSManagedObjectContext * context = [self managedObjectContext]; 

NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription * entity1 = [NSEntityDescription entityForName:@EventinManagedObjectContext:context];

[fetchRequest setEntity:entity1];

NSError * error;

NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:& error];

if(array == nil){

NSLog(@Testing:No results found);

} else {

NSLog(@测试:%d个结果找到了,[array count]);
}

NSData * dataBytes = [[array objectAtIndex:0] data];

image = [UIImage imageWithData:dataBytes];

[fetchRequest release];


}

@catch(NSException * exception){

NSLog(@within exception);
}

错误:
测试:3找到的结果。
2010-07-28 23:27:51.343 IMG_REF [11657:207] - [事件数据]:无法识别的选择器发送到实例0x5e22ce0
2010-07-28 23:27:51.344 IMG_REF [11657: 207] ***由于未捕获异常NSInvalidArgumentException终止应用程序,原因:' - [事件数据]:无法识别的选择器发送到实例0x5e22ce0'
***首次调用堆栈:
b $ b 0 CoreFoundation 0x02566919 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x026b45de objc_exception_throw + 47
2 CoreFoundation 0x0256842b - [NSObject(NSObject)doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x024d8116 ___ forwarding___ + 966
4 CoreFoundation 0x024d7cd2 _CF_forwarding_prep_0 + 50
5 IMG_REF 0x00003b06 - [IMG_REFViewController showAction] + 353
6 UIKit 0x002bae14 - [UIApplication sendAction:to:from:forEvent:] + 119
7 UIKit 0x004c214b - [UIBarButtonItem(UIInternal)_sendAction:withEvent:] + 156
8 UIKit 0x002bae14 - [UIApplication sendAction:to:from:forEvent:] + 119
9 UIKit 0x003446c8 - [UIControl sendAction:to :forEvent:] + 67
10 UIKit 0x00346b4a - [UIControl(Internal)_sendActionsForEvents:withEvent:] + 527
11 UIKit 0x003456f7 - [UIControl touchesEnded:withEvent:] + 458
12 UIKit 0x002de2ff - [UIWindow _sendTouchesForEvent:] + 567
13 UIKit 0x002c01ec - [UIApplication sendEvent:] + 447
14 UIKit 0x002c4ac4 _UIApplicationHandleEvent + 7495
15 GraphicsServices 0x02dccafa PurpleEventCallback + 1578
16 CoreFoundation 0x02547dc4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
17的CoreFoundation 0x024a8737 __CFRunLoopDoSource1 + 215
18的CoreFoundation 0x024a59c3 __CFRunLoopRun + 979
19的CoreFoundation 0x024a5280 CFRunLoopRunSpecific + 208
20的CoreFoundation 0x024a51a1 CFRunLoopRunInMode + 97
21 GraphicsServices 0x02dcb2c8 GSEventRunModal + 217
22 GraphicsServices 0x02dcb38d GSEventRun + 115
23 UIKit 0x002c8b58 UIApplicationMain + 1160
24 IMG_REF 0x00002aac main + 102
25 IMG_REF 0x00002a3d start + 53

在抛出NSException的实例后调用终止

注意:执行NSData * dataBytes = [[array objectAtIndex:0] data];线。



我花了一个很多时间与此。请帮助我!

解决方案

当您检索图片时,您正在执行获取请求并将结果存储在变量数组,表示数组包含一个NSArray的Event对象。然后,您指定:

  dataBytes = [array objectAtIndex:0];  

这意味着你声明为NSData的 dataBytes 现在实际上是一个Event的实例。然后当你去初始化图像时, imageWithData:的部分实现调用 length 您的NSData对象,但实际上是一个Event对象,因此错误消息。



您应该将您的代码调整为:

  dataBytes = [[array objectAtIndex:0] imgPng];  

这样,你从数组中获取第一个事件对象,然后获取它的 imgPng 属性(一个NSData的实例,这是你想要的)。



注意,您的 dataBytes 使用 alloc - init 可能是无关紧要的,因为您之后立即将 dataBytes 更改为来自您的事件的数据。


In my app, I am trying to save and retrieval of an image in core data. I am able to save an image successfully after convention of UIimage into NSData, But when I am trying to get an image as NSData it shows output as given below,

case 1: When trying to display as a string from DB.

 <Event: 0x5b5d610> (entity: Event; id: 0x5b5ce30 <x-coredata://F51BBF1D-6484-4EB6-8583-147E23D9FF7B/Event/p1> ; data: <fault>)

case 2: When trying to display as Data

 [Event length]: unrecognized selector sent to instance 0x5b3a9c0
 2010-07-28 19:11:59.610 IMG_REF[10787:207] *** Terminating app due to uncaught exception    'NSInvalidArgumentException', reason: '-[Event length]: unrecognized selector sent to instance 0x5b3a9c0'

My code,

to save:

NSManagedObjectContext *context = [self managedObjectContext];

newsObj = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:context];

NSURL *url = [NSURL URLWithString:@"http://www.cimgf.com/images/photo.PNG"];

NSData *data = [[NSData alloc] initWithContentsOfURL:url];

uiImage = [UIImage imageWithData:data];

NSData * imageData = UIImagePNGRepresentation(uiImage);

[newsObj setValue:imageData forKey:@"imgPng"];

NSError *error;

@try{

    if (managedObjectContext != nil) {

        if (![managedObjectContext save:&error]) {

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

            NSString * infoString = [NSString stringWithFormat:@"Please check your connection and try again."];

            UIAlertView * infoAlert = [[UIAlertView alloc] initWithTitle:@"Database Connection Error" message:infoString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

            [infoAlert show];

            [infoAlert release];
        } 
    }

}@catch (NSException *exception) {

    NSLog(@"inside exception");
}

to retrieve,

    NSManagedObjectContext *context = [self managedObjectContext];

    NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity1 = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];

    [fetchRequest setEntity:entity1];

    NSError *error;

    NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    if (array == nil) {

        NSLog(@"Testing: No results found");

    }else {

        NSLog(@"Testing: %d Results found.", [array count]);
    }

    NSData * dataBytes = [[array objectAtIndex:0] data];

    image = [UIImage imageWithData:dataBytes];

    [fetchRequest release]; 


}

@catch (NSException *exception) {

    NSLog(@"inside exception");
}

Error:
   Testing: 3 Results found.
   2010-07-28 23:27:51.343 IMG_REF[11657:207] -[Event data]: unrecognized selector sent       to  instance 0x5e22ce0
   2010-07-28 23:27:51.344 IMG_REF[11657:207] *** Terminating app due to uncaught   exception 'NSInvalidArgumentException', reason: '-[Event data]: unrecognized selector sent  to instance 0x5e22ce0'
  *** Call stack at first throw:
  (
0   CoreFoundation                      0x02566919 __exceptionPreprocess + 185
1   libobjc.A.dylib                     0x026b45de objc_exception_throw + 47
2   CoreFoundation                      0x0256842b -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3   CoreFoundation                      0x024d8116 ___forwarding___ + 966
4   CoreFoundation                      0x024d7cd2 _CF_forwarding_prep_0 + 50
5   IMG_REF                             0x00003b06 -[IMG_REFViewController showAction] + 353
6   UIKit                               0x002bae14 -[UIApplication sendAction:to:from:forEvent:] + 119
7   UIKit                               0x004c214b -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 156
8   UIKit                               0x002bae14 -[UIApplication sendAction:to:from:forEvent:] + 119
9   UIKit                               0x003446c8 -[UIControl sendAction:to:forEvent:] + 67
10  UIKit                               0x00346b4a -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
11  UIKit                               0x003456f7 -[UIControl touchesEnded:withEvent:] + 458
12  UIKit                               0x002de2ff -[UIWindow _sendTouchesForEvent:] + 567
13  UIKit                               0x002c01ec -[UIApplication sendEvent:] + 447
14  UIKit                               0x002c4ac4 _UIApplicationHandleEvent + 7495
15  GraphicsServices                    0x02dccafa PurpleEventCallback + 1578
16  CoreFoundation                      0x02547dc4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
17  CoreFoundation                      0x024a8737 __CFRunLoopDoSource1 + 215
18  CoreFoundation                      0x024a59c3 __CFRunLoopRun + 979
19  CoreFoundation                      0x024a5280 CFRunLoopRunSpecific + 208
20  CoreFoundation                      0x024a51a1 CFRunLoopRunInMode + 97
21  GraphicsServices                    0x02dcb2c8 GSEventRunModal + 217
22  GraphicsServices                    0x02dcb38d GSEventRun + 115
23  UIKit                               0x002c8b58 UIApplicationMain + 1160
24  IMG_REF                             0x00002aac main + 102
25  IMG_REF                             0x00002a3d start + 53
 )
 terminate called after throwing an instance of 'NSException'

Note: Above error is coming when going to execute NSData * dataBytes = [[array objectAtIndex:0] data]; line.

I spent a lot of time with this. Please help me out!

解决方案

When you retrieve the image, you're performing the fetch request and storing the results in the variable array, meaning array holds an NSArray of Event objects. Then, later, you assign:

dataBytes = [array objectAtIndex:0];

This means that dataBytes, which you declared as NSData, is now actually an instance of Event. Then when you go to initialize the image, part of the implementation of imageWithData: calls length on what it expects to be your NSData object, but is actually an Event object, hence the error message.

You should adjust your code to read:

dataBytes = [[array objectAtIndex:0] imgPng];

That way, you're getting the first Event object out of the array, then fetching its imgPng property (an instance of NSData, which is what you want).

As a side note, your declaration of dataBytes using the alloc-init on the line above may be extraneous, since you change dataBytes to be the data from your Event immediately afterwards.

这篇关于保存和检索UIImage在CoreData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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