Blade
Blade

Reputation: 1437

Trying to retrieve image - getting EXC_BAD_ACCESS Error

I saved a picture to NSData with UserDefaults and now want it to be retrieved in a tableview cell.

Here is what I put in the ViewDidLoad of the TableView.m

NSData *imageData;
imageData = [NSKeyedArchiver archivedDataWithRootObject:yourUIImage];
[[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"image"];

And here is what I put in the TableView cellforRowatIndex

cell.imageView.image = [UIImage imageWithData:@"bild"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

However when I start the programe I get an EXC_BAD_ACCESS Error at the cell.imageView.image line together with a "incompatible pointer types sending "NSString*" to paramater of type "NSData*""

Here is btw how I save the image in the first place:

if ([[NSUserDefaults standardUserDefaults] objectForKey:@"image"] == nil) { 
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];

    NSData *imageData;
    UIImage *yourUIImage;
    imageData = [NSKeyedArchiver archivedDataWithRootObject:yourUIImage];
    [[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"image"];

Upvotes: 1

Views: 413

Answers (2)

Costique
Costique

Reputation: 23722

Use NSKeyedUnarchiver as a counterpart to NSKeyedArchiver like this:

NSData *imageData = [[NSUserDefaults standardUserDefaults] dataForKey: @"image"];
cell.imageView.image = [NSKeyedUnarchiver unarchiveObjectWithData: imageData];

Upvotes: 2

zaph
zaph

Reputation: 112857

The error message:
"incompatible pointer types sending "NSString*" to paramater of type "NSData*""
An NSString was supplied as a parameter instead of an NSData.
Looking at your method invocation line:

cell.imageView.image = [UIImage imageWithData:@"bild"];

The parameter is an NSString: @"bild".
The documentation for UIImage imageWithData is:
data: The image data. This can be data from a file or data you create programmatically.
you need to get the image data from the NSArchive and supply it (the data) to the imageWithData method.

It always pays to read and understand the error messages even it it takes some time to figure them out.

Upvotes: 1

Related Questions