Search code examples
iosobjective-cnsarrayuipickerviewnstimer

How to link a UIPickerView array to a integer property in another class iOS


I have a UIPickerView array of seconds which i would like to link to an NSTimer.

in quiz.h file
@property (strong, nonatomic) IBOutlet UIPickerView *timePicker;

i have the array in quiz.m file:

- (void)viewDidLoad {
[super viewDidLoad];

self.pickerData = @[@"1 second", @"2 seconds", @"3 seconds", @"4 seconds", @"5 seconds"];

self.timePicker.dataSource = self;
self.timePicker.delegate = self;
}
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    [self.pickerData objectAtIndex:[self.timePicker selectedRowInComponent:0]];
}

and i would like to link this array of seconds to a property in the imageview.h file

@property (nonatomic, assign) int seconds;

how can i do that within the quiz.m file?

i am trying:

ImageViewController *ivc = [[ImageViewController alloc] init];
        ivc.seconds = [self.timePicker selectedRowInComponent:0]; // warning displays conversion loses integer precision

what do i add in ivc.seconds to link it to the picker array and get the number seconds in each row when selected?

i want to link the seconds to a NSTimer.

 [NSTimer scheduledTimerWithTimeInterval:self.seconds target:self selector:@selector(timeout)
                               userInfo:nil repeats:NO];

timeout method pops to rootview


Solution

  • make self.pickerData = @[@"1", @"2", @"3", @"4", @"5"]; and in picker methods,

    - (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
    {
        int value = [[self.pickerData objectAtIndex:row] intValue];
        NSString *secondString = (value > 1) ? @"seconds" : @"second"
        NSString *title = [NSString stringWithFormat:@"%@ %@", [self.pickerData objectAtIndex:row], secondString];
        return title;
    }
    

    and on creating

    NSInteger row = [self.timePicker selectedRowInComponent:0];
    ImageViewController *ivc = [[ImageViewController alloc] init];
    ivc.seconds = [[self.pickerData objectAtIndex:row] intValue];
    

    to show the count down timer, set up tim er first

    timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(setTimeToLabel) userInfo:nil repeats: YES];
    

    then in setTimeToLabel method

    -(void) setTimeToLabel 
    {
        if (self.seconds != 0) { 
            self.timeLabel.text = [NSString stringWithFormat:@"%d", self.seconds]; 
            self.seconds = self.seconds - 1;
        } else {
            [timer invalidate];
        }
    }