Friday, December 5, 2008

Error when switching views on iPhone

I was developing a application with multiple views hanging off one application controller. When I received the following error during run-time:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[iWCFDemoViewController dataviewView]: unrecognized selector sent to instance 0x5264c0'

The line of code which failed was :
- (void)switchToNewView:(id)sender
{
// get the view that's currently showing
UIView *currentView = self.view;
// get the the underlying UIWindow, or the view containing the current view view
UIView *theWindow = [currentView superview];
// remove the current view and replace with myView1
[currentView removeFromSuperview];
[theWindow addSubview:self.dataviewView]; // <<<--- Crash on this line
}


The header file seemed to be created correctly showing:
@interface iWCFDemoViewController : UIViewController {
IBOutlet UIView *generateView;
IBOutlet UIView *dataviewView;
}

@property(nonatomic, retain) UIView *generateView;
@property(nonatomic, retain) UIView *dataviewView;

- (void) switchToNewView:(id)sender;
@end

I checked the NIB file in Interface builder and everything was connected up correctly.

The solution was to make two minor changes to the code:
First the header was changed to:
IBOutlet UIView *_generateView;
IBOutlet UIView *_dataviewView;

Then in the view controller, just under the @implementation line, I added the two lines:
@synthesize dataviewView = _generatewView;
@synthesize dataviewView = _dataviewView;

I''m not really sure what the difference is between these two implementations as all I seem to be doing moving the pointer reference to a duplicate variable, however it seemed to work fine after that.