且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当用户同时旋转组件时,UIPickerView会崩溃应用程序

更新时间:2023-02-02 13:46:22

实际上我的假设是错的 - 选中的行不是未定义的或是零,但是当你旋转时它会快速变化。问题是你在numberOfRowsInComponent中返回的数字取决于该方法运行时旋转拨号的位置,但是当titleForRow运行时,第一个组件位于不同的行上,并且您正在尝试访问不在存在。要修复它,你应该定义一个属性sRow,在numberOfRowsInComponent中为它赋值,然后在titleForRow中使用相同的值(不要像你现在那样重新分配),而不是获取新值。

Actually I was wrong in my supposition -- the selected row is not undefined or nil, but it's changing rapidly while you spin. The problem is that the number you return in numberOfRowsInComponent depends on where the spinning dial is when that method runs, but by the time titleForRow runs, the first component is on a different row, and you're trying to access rows that don't exist. To fix it, you should define a property sRow, assign it a value in numberOfRowsInComponent, and then use that same value (don't re-assign like you're doing now) in titleForRow, rather than getting a new value.

@property (nonatomic) NSInteger sRow;

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        // Left picker
        return [leftPickerDataSource count];
        //[foodPicker selectRow:0 inComponent:1 animated:YES];
    }
    else {
        // Right picker
        self.sRow = [foodPicker selectedRowInComponent:0];
        if ([[leftPickerDataSource objectAtIndex:self.sRow] isEqual:@"Vegetables"])
            return [vegetablesDataSource count];
        else if ([[leftPickerDataSource objectAtIndex:self.sRow] isEqual:@"Eggs"])
            return [eggsDataSource count];
        else if ([[leftPickerDataSource objectAtIndex:self.sRow] isEqual:@"Pasta"])
            return [pastaDataSource count];
        else if ([[leftPickerDataSource objectAtIndex:self.sRow] isEqual:@"Rice"])
            return [riceDataSource count];
        else if ([[leftPickerDataSource objectAtIndex:self.sRow] isEqual:@"Meat"])
            return [meatDataSource count];
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        // Left picker
        return [leftPickerDataSource objectAtIndex:row];
    }
    else {
        // Right picker
        if ([[leftPickerDataSource objectAtIndex:self.sRow] isEqual:@"Vegetables"])
            return [vegetablesDataSource objectAtIndex:row];
        else if ([[leftPickerDataSource objectAtIndex:self.sRow] isEqual:@"Eggs"])
            return [eggsDataSource objectAtIndex:row];
        else if ([[leftPickerDataSource objectAtIndex:self.sRow] isEqual:@"Pasta"])
            return [pastaDataSource objectAtIndex:row];
        else if ([[leftPickerDataSource objectAtIndex:self.sRow] isEqual:@"Rice"])
            return [riceDataSource objectAtIndex:row];
        else if ([[leftPickerDataSource objectAtIndex:self.sRow] isEqual:@"Meat"])
            return [meatDataSource objectAtIndex:row];
    }
}