views:

11

answers:

1

I am having trouble loading from saved data an instance of a custom class that conforms to the NSCoding protocol. My class has a UIImage property and when I assign a new UIImage to it the program crashes with an exc_bad_access.

In the view controller I declare my object like so:

@interface SomeViewController : UIViewController  {
    IBOutlet UIImageView *imageView;
    SomeClass *myObject;
 }

@property (nonatomic, retain) SomeClass *myObject;
@property (nonatomic, retain) IBOutlet UIImageView *imageView;

Then in the .m file it is used as following:

@synthesize myObject;
@synthesize imageView;

-(void)viewDidLoad{
  myObject = [NSKeyedUnarchiver unarchiveObjectWithFile:someDataPath];
  imageView.image = myObject.image;
}

So far so good. But later I pick a new image and try to set it to the "image" property of myObject, and this throws an exc_bad_access

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  [picker dismissModalViewControllerAnimated:YES];
  UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
  [imageView setImage:image];
   myObject.image = image;
}

As far as I can tell from single-stepping through the code, it is the last line which is causing the exc_bad_access. What am I doing wrong?

+1  A: 

You have to retain myObject:

self.myObject = [NSKeyedUnarchiver unarchiveObjectWithFile:someDataPath];
Ole Begemann
So what is the difference from using self.myObject here instead of just myObject?
Jacob Lyles
The difference is that a setter is called that retains the object. You should read some introduction to Cocoa/Obj-C if that's not clear to you.
Ole Begemann
ah, I see. So I guess I should always use self.myObject instead of directly accessing it, at least for assignment purposes. I will read Apple's objective-c docs one more time, maybe this time it will stick.
Jacob Lyles