0

私は完全に Android のバックグラウンドから iOS を学ぼうとしています。超初心者の質問で申し訳ありませんが、アプリ全体で別のクラスとして何度も再利用できる UIPickerView Util クラスを構築したいと考えており、EXC_BAD_ACCESSメッセージを受け取りましたが、その理由がわかりません。だから私は2つの質問があります:

  1. これを別のクラスとして分離することについては何も見たことがありません。これは、この問題を処理する不適切な方法であるためですか?

  2. EXC_BAD ACCESS メッセージを表示するこの基本的な (ほとんど生成された) コードの何が問題になっていますか? これはメモリの問題に関連していると読みました。私は ARC を使用していますが、なぜこれが問題なのですか?

これが私が構築しようとしているクラスの始まりです。

ヘッダーファイル

#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]];

ご協力いただきありがとうございます。ただ学ぼうとしているだけです!

4

1 に答える 1

0

showPicker で何をしていますか? showPicker は、実際には表示されないため誤解を招きます。フレーム付きの pickerView のみを返します。ある時点で、addSubview を使用してビューに追加するか、UIPopoverController などを使用する必要があります。

メソッドのスコープ内でView Controllerクラスを作成しているだけの場合、そのメソッドの実行が完了するとすぐに解放されます。その後、すべての賭けはオフになります。ピッカーはデリゲート (ビュー コントローラー) にアクセスしようとしていますが、ビュー コントローラーは解放されているため、どこにも見つかりません。

いくつかの使用コードを投稿する必要があります。このコードはそれ自体で機能するはずですが、それはあなたの使い方です。

また、単純なビューを「制御」するためだけに UIViewController を使用する必要はありません。カスタム クラスを作成し、NSObject をサブクラス化することを検討してください。

編集:投稿されたコードを見た後、私の疑いは正しかった。PickerTools インスタンスを「保持」する必要があります。つまり、「ピッカー」変数 (再び誤解を招く) を、呼び出し元のビュー コントローラーの強力なプロパティとして保存する必要があります。ピッカービューをサブビューとして追加した直後に解放されます。pickerView はスーパービューによって保持されているため生きていますが、それを保持するオブジェクト (デリゲート「ピッカー」) は死んでいます。わかる?

于 2012-11-26T23:36:52.850 に答える