views:

139

answers:

1

hi guys,

I have a class with 4 arrays: tab_1,tab_2,tab_3 and tab_T. I set the picker's delegate and datasource to self (which is the class containing the arrays).

The picker is called when textfields begin editing. I return NO in order to prevent the keyboard from being shown. I have a method animating the picker instead.

Depending on which textfield is touched i do: tab_T=tab_1; or 2 or 3

In my opinion this assignment makes tab_T the datasource of the picker. Is this assignment really binding the array tab_T to the datasource? Is there a way to manually assign it? i'm sure there is. But picker.datasource=tab_1 doesn't work. i got a " warning: class 'NSMutableArray' does not implement the 'UIPickerViewDataSource' protocol".

Its my first app maybe i am forgetting a step i did at the early ages of my app.

Looking forward to anyone willing to help.

Wallou

+1  A: 

A UIPickerView's datasource has to be a class that implements the UIPickerViewDataSource protocol. The populating of the picker view is done in these two methods:

– numberOfComponentsInPickerView:  
– pickerView:numberOfRowsInComponent: 

Since NSArray doesn't implement the protocol using:

pickerView.datasource=someArray;

... generates the error you've seen saying the array does not implement the protocol.

The first thing you need to do is to declare that your controller implements the protocol like so:

@interface MyControllerClass: UIViewController <UIPickerViewDataSource,UIPickerViewDelegate> 

then you need to implement the protocol's methods which will look something like:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1; //or whatever
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [self.tab_T count]; // assuming just one component
}

To actually populate the components, you need the UIPickerViewDelegate methods. (I know it seems that the datasource should provide, you know, data but for some reason they have it backwards.)

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [self.tab_T objectAtIndex:row]; //assuming one component
}

The key idea here is that the objects that implement the datasource and delegate methods serve as the interface between the picker and whatever data structure actually holds the data. In this case, its just simple arrays but it could be anything including Core Data, SQL or downloaded from a URL.

The pickerview never directly deals with the data structure at all. It's always the object/s that implement the datasource and delegate methods that do the interaction.

TechZen
morning TechZen,Ok,thanks for this answer, clear and complete.I do understand better now the behavior of the picker.Bye, Wallou
wallou