构建UIPickerView Util类

时间:2012-11-26 23:23:49

标签: ios uipickerview exc-bad-access

我正在尝试从完全Android背景学习iOS。对于超级noob问题很抱歉,但我希望构建一个UIPickerView Util类,可以在我的应用程序中作为一个单独的类重复使用,我收到 EXC_BAD_ACCESS 消息,我就是不知道为什么。所以我有两个问题:

  1. 我没有看到任何关于将它作为一个不同的类分开的事情,这是因为这是处理这个问题的一种不正确的方法吗?

  2. 这个基本(主要是生成的)代码会给我EXC_BAD ACCESS消息有什么问题?我读过这与内存问题有关。我正在使用ARC,为什么这是一个问题?

  3. 以下是我正在尝试构建的类的开头。

    标头文件

    #import <UIKit/UIKit.h>
    
    @interface PickerTools : UIViewController<UIPickerViewDelegate>
    
    @property (strong, nonatomic)UIPickerView* myPickerView;
    
    -(UIPickerView*)showPicker;
    
    @end
    

    实施文件

    #import "PickerTools.h"
    
    @implementation PickerTools
    
    @synthesize myPickerView;
    
    - (UIPickerView*)showPicker {
        myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 320, 200)];
        myPickerView.delegate = self;
        myPickerView.showsSelectionIndicator = YES;
        return myPickerView;
    }
    
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:        (NSInteger)component {
        // Handle the selection
    }
    
    // tell the picker how many rows are available for a given component
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
        NSUInteger numRows = 5;
    
        return numRows;
    }
    
    // tell the picker how many components it will have
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
        return 1;
    }
    
    // tell the picker the title for a given component
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
        NSString *title;
        title = [@"" stringByAppendingFormat:@"%d",row];
    
        return title;
    }
    
    // tell the picker the width of each row for a given component
    - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
        int sectionWidth = 300;
    
        return sectionWidth;
    }
    
    @end
    

    以下是我从UITableViewController类中的方法调用它的方法:

    PickerTools *picker = [[PickerTools alloc]init];
    [[self view]addSubview:[picker showPicker]];
    

    再次感谢您的帮助!只是想学习!

1 个答案:

答案 0 :(得分:0)

你在使用showPicker做什么? showPicker具有误导性,因为它实际上并没有显示出来。它只返回带框架的pickerView。在某些时候,您需要使用addSubview将其添加到视图中或使用UIPopoverController或其他东西。

如果您只是在方法范围内创建视图控制器类,那么一旦该方法运行完毕,它就会被释放。然后所有的赌注都关闭了。选择器正在尝试访问委托(它是视图控制器),但视图控制器无处可寻,因为它已被释放。

您必须发布一些使用代码。这个代码本身应该可以工作,但这就是你使用它的方式。

此外,您不必仅使用UIViewController来“控制”简单视图。考虑制作一个自定义类,然后只是升级NSObject。

编辑: 在查看您发布的代码后,我的怀疑是正确的。您需要“保留”PickerTools实例。这意味着,您需要将“picker”变量(再次误导)保存为调用视图控制器上的强属性。它会在您将pickerview添加为子视图后立即发布。 pickerView是活着的,因为它的高级视图保留了它,但是持有它的对象(委托“picker”)已经死了。合理?

相关问题