【问题标题】:Creating a delegate and dataSource for UIPickerView为 UIPickerView 创建委托和数据源
【发布时间】:2014-07-24 21:55:08
【问题描述】:

我正在尝试在单独的文件中为 UIPickerView 创建委托和数据源。在 ViewController 我有:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIPickerView *myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 320, 200)];

    MonthPicker *monthPicker = [[MonthPicker alloc] init];
    myPickerView.delegate = monthPicker;
    myPickerView.dataSource = monthPicker;
    myPickerView.showsSelectionIndicator = YES;
    [self.view addSubview:myPickerView];
}

MonthPicker.h

#import <UIKit/UIKit.h>

@interface MonthPicker : NSObject<UIPickerViewDelegate,UIPickerViewDataSource>

@end

MonthPicker.m

#import "MonthPicker.h"

@implementation MonthPicker


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return 7;
}

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

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return @"yyy";
}

@end

目前我只使用占位符值来让委托工作。 Everyting 编译正常,但是当我运行应用程序并转到其中包含选择器的视图时,它会在控制台中崩溃并显示 0 条错误消息。

我得到的唯一消息是:线程 1:EXC_BAD_ACCESS (code=2,address=0x0) 但这对我没有任何帮助。

我还尝试用 NSLog 覆盖委托中的 dealloc 方法,似乎在崩溃发生之前,它被释放了,我觉得这很奇怪。

我错过了什么?

谢谢。

【问题讨论】:

    标签: objective-c delegates uipickerview uipickerviewdelegate


    【解决方案1】:

    问题可能是在 viewDidLoad 方法结束时,monthPicker 对象被释放。

    尝试让monthPicker成为一个属性,看看是否可行

    【讨论】:

    • 这绝对是问题所在。选择器视图不保留其委托/数据源,因此必须保留在其他地方。
    • 你们摇滚,非常感谢,它现在运行良好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多