I am trying to create a delegate and a dataSource for a UIPickerView in a separate file. In the ViewController i have:
- (void)viewDidLoad
{
[super viewDidLoad];
UIPickerView *myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 320, 200)];
MonthPicker *monthPicker = [[MonthPicker alloc] init];
myPickerView.delegate = monthPicker;
myPickerView.dataSource = monthPicker;
myPickerView.showsSelectionIndicator = YES;
[self.view addSubview:myPickerView];
}
MonthPicker.h
#import <UIKit/UIKit.h>
@interface MonthPicker : NSObject<UIPickerViewDelegate,UIPickerViewDataSource>
@end
MonthPicker.m
#import "MonthPicker.h"
@implementation MonthPicker
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return 7;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return @"yyy";
}
@end
At the moment i am using just placeholder values to get the delegate to work. Everyting compiles ok, but when i run the app and go to the view that has the picker in it, it crashes with 0 error messages in the console.
The only message i get is: Thread 1:EXC_BAD_ACCESS (code=2,address=0x0) but this does not help me at all.
I also tried overriding the dealloc method in the delegate with an NSLog, and it appears that before the crash occurs, it gets deallocated, which i find very wierd.
What am i missing?
Thank you.
the problem may be that at the end of the viewDidLoad method, the monthPicker object gets deallocated.
try to make monthPicker be a property instead, see if that works