Search code examples
iphoneobjective-cios6nsarrayuipickerview

Data from array is not showing up in the pickerView


I am trying to do Single-Component Picker example Beginning iOS 6 Development Book, almost every thing works fine but Data from array is not showing up in the pickerView Please Help

Here is my .h file

<UIPickerViewDataSource , UIPickerViewDelegate>
{
    IBOutlet UIPickerView *singlePicker;
    NSArray *chaNames;
}

@property (strong, nonatomic) IBOutlet UIPickerView *singlePicker;
@property (strong, nonatomic) NSArray *chaNames;



- (IBAction)buttonPressed:(id)sender;


@end

And here is .m file

#import "SSPSingleComponentViewController.h"

@interface SSPSingleComponentViewController ()

@end

@implementation SSPSingleComponentViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.chaNames = @[@"Luke",@"Leia",@"Han",@"Chewbacca",@"Artoo", @"Threepio",@"lando"];
}



- (IBAction)buttonPressed:(id)sender {

    NSInteger row = [self.singlePicker selectedRowInComponent:0];
    NSString *selected = self.chaNames[row];
    NSString *title = [[NSString alloc]initWithFormat:@"You slected %@", selected];

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"OutPut is : " message:title delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

    [alert show];
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
    return [self.chaNames count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView
            titleForRow:(NSInteger)row
           forComponent:(NSInteger)component
{
    return[self.chaNames objectAtIndex:row];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

Please Help Thanks in advance :)


Solution

  • You need to alloc your NSArray object as follows:

    self.chaNames = [NSArray alloc] initWithObjects:@"Luke",@"Leia",@"Han",@"Chewbacca",@"Artoo", @"Threepio",@"lando"];
    

    Edit:

    you also need to set singlePicker.datasource = self; and singlePicker.delegate = self; within viewDidLoad or hook it up correctly with IB (both the delegate and datasource)

    -(void)viewDidLoad {
    
        self.chaNames = [NSArray alloc] initWithObjects:@"Luke",@"Leia",@"Han",@"Chewbacca",@"Artoo", @"Threepio",@"lando"];
    }