2010-07-28 7 views
17

내 응용 프로그램에서 핵심 데이터에서 이미지를 저장하고 검색하려고합니다. 이미지를 성공적으로 NSim에 UIimage 후 이미지를 저장할 수 있지만 NSData 같이 이미지를 얻으려고 할 때 아래와 같이 출력을 보여줍니다.저장 및 CoreData UIImage 검색

경우 1 : DB에서 문자열로 표시하려고 할 때.

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

경우 2 : 데이터로

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"); 
} 

가 검색

[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' 

내 코드,

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' 

주를 표시하려고 할 때 : 오류 위의 경우에오고있다 NSData * dataBytes = [[배열 objectAtIndex : 0] data]; 선. Data Model http://www.freeimagehosting.net/uploads/7c286931cc.png

나는 이것으로 많은 시간을 보냈다. 제발 도와주세요!

+0

이미지를 NSData에 저장하는 방법과 검색 방법에 관한 코드를 추가하십시오. 애매한 오류 메시지가 많이 도움이되지 않습니다. – iwasrobbed

+0

@IWasRobbed는 귀하의 응답에 감사 드리며이를 제 코드에 넣습니다. 내가 뭘 잘못했는지 알아봐. – Sivanathan

답변

7

이미지를 검색 할 때 가져 오기 요청을 수행하고 결과를 변수 array에 저장합니다. 즉, array에 이벤트 객체의 NSArray가 있음을 의미합니다. 그런 다음, 나중에, 당신은 지정 : 이것은 당신이있는 NSData로 선언 dataBytes가, 지금은 이벤트의 실제 인스턴스 것을 의미

dataBytes = [array objectAtIndex:0];

. 그런 다음 이미지 초기화를 수행 할 때 imageWithData: 구현 부분은 length을 NSData 객체로 예상하지만 실제로는 Event 객체이므로 오류 메시지입니다.

당신이 읽을 수 있도록 코드를 조정해야합니다 :

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

그런 식으로, 당신은 무엇을 자사의 imgPng 재산 (을 NSData의 인스턴스를 가져 오는 한 후, 배열에서 첫 번째 이벤트 객체를 얻고있는 당신 필요). 보조 노트로

alloc 사용 dataBytes 당신의 선언 - 당신이 dataBytes을 변경하기 때문에 위의 외부있을 수 있습니다 라인에 init 즉시 나중에 이벤트에서 데이터가 될 수 있습니다.

+0

@Tim 내가 말한대로 변경했지만 여전히 동일한 오류를 보여줍니다. – Sivanathan

+0

* 정확한 * 같은 오류가 있습니까? 위의 질문을 편집하고 업데이트 후 오류를 복사/붙여 넣기 할 수 있습니까? 감사. – Tim

+0

@Tim 예. 붙여 넣기를하고 응답 해 주셔서 감사합니다. – Sivanathan

39

확실하지 당신이 입수 한 경우이 아직 밖으로 곧게하지만, 다음과 같이 내가 코어 데이터에 UIImage 객체를 저장/검색 할 수 있어요 :

NSData *imageData = UIImagePNGRepresentation(yourUIImage); 
[newManagedObject setValue:imageData forKey:@"image"]; 

및로드 :

저장하기 :

NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath]; 
UIImage *image = [UIImage imageWithData:[selectedObject valueForKey:@"image"]]; 
[[newCustomer yourImageView] setImage:image]; 

희망이 있습니다. 핵심 데이터와방법으로 데이터베이스에서 이미지를 가져 오는 UITableView을 사용하고 있습니다.

+1

나는 샘플 코드가 좋아. 그러나 UIImage가 UIImage * –

26

다음은 올바른 해결책입니다.

1) 코어 데이터로 보관하여 UIImage :

NSData* coreDataImage = [NSData dataWithData:UIImagePNGRepresentation(delegate.dancePhoto)]; 

는 "coreDataImage는"유형 NSData의 있는지 확인합니다. 모델에서 "coreDataImage"에 대해 유형을 "Binary data"로 설정해야합니다.

2) 코어 데이터에서 보유하고있는 도서관을 찾는있는 UIImage는 : 그것에있다 전부

UIImage* image = [UIImage imageWithData:selectedDance.danceImage]; 

는 잘 작동합니다.

+1

유형임을 언급하는 것이 좋을 것입니다. Brian은 이미 거의 똑같은 해결책으로 대답했습니다. – Detra83

+1

이미 NSData 객체를 반환하므로 UIImagePNGRepresentation을 NSData 초기화 프로그램에 전달할 필요가 없습니다. – Gargoyle

7

내가 사용한 솔루션은 벨로우즈 카테고리를 만드는 것이 었습니다. 프로젝트가 제대로 작동하려면 프로젝트에 필요합니다. 을 NSData

있는 UIImage + NSCoding.h

@interface UIImage (UIImage_NSCoding) <NSCoding> 
- (void)encodeWithCoder:(NSCoder *)aCoder; 
- (id)initWithCoder:(NSCoder *)aDecoder; 
@end 

있는 UIImage + NSCoding.m

#import "UIImage+NSCoding.h" 

@implementation UIImage (UIImage_NSCoding) 

- (void)encodeWithCoder:(NSCoder *)aCoder 
{ 
    NSData *imageData = UIImagePNGRepresentation(self); 
    [aCoder encodeDataObject:imageData]; 
} 

- (id)initWithCoder:(NSCoder *)aDecoder 
{ 
    [self autorelease]; 
    NSData* imageData = [aDecoder decodeDataObject]; 
    self = [[UIImage alloc] initWithData:imageData]; 
    return self; 
} 
@end 
+0

네, 클래스가 NSCoding 프로토콜을 준수하면 NSKeyedUnarchiveFromDataTransformerName (코어 데이터의 표준)을 사용할 수 있기 때문에 이것이 가장 쉬운 방법입니다. – CarlJ

+0

혼란 스럽습니다. NSKeyedUnarchiveFromDataTransformerName이 사용 된 곳이 없습니다. –

+0

실제로 UIImage는 코드를 추가 할 필요없이 NSCoding을 준수합니다. 그래서'Transformable' 속성으로 사용할 수 있습니다. [코드 작성없이 CoreData에 UIImage 저장하기] 참조 (http://upips.org/yonat/uiimage-in-coredata/) – Yonat