In a seemingly never ending effort to learn more about iphone development, I have been playing around with some of the source code available through apples developer website
The compiler is trying to help you out. You're overriding the onoff instance variable in your viewDidLoad;
thus, that's never getting set. In your -flip: method, you're referencing a nil controller. There are two ways to fix this:
(a) Get rid of the local declaration of onoff, and just use your instance variable
(b) Cast the sender argument to -flip: as a UISwitch
, and access that:
- (IBAction) flip: (id) sender {
UISwitch *onoff = (UISwitch *) sender;
NSLog(@"%@", onoff.on ? @"On" : @"Off");
}
Steve, I'm sorry if I misunderstood your question. Did you actually create the UISwitch
and add it to the view hierarchy? Your controller's -loadView
or -viewDidLoad
implementation should have code like the following:
// Use the ivar here
onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
[onoff addTarget: self action: @selector(flip:) forControlEvents: UIControlEventValueChanged];
// Set the desired frame location of onoff here
[self.view addSubview: onoff];
[onoff release];