1

クラス:

次のメソッドでは、ブロックを使用して共通デリゲートを置き換えます。大丈夫ですか?メソッド内のブロックは、didSelectRowAtIndexPath共通のデリゲートを置き換えるために使用しますが、実行すると、テーブル セルをクリックするとコードがクラッシュします。

typedef void (^Block)(NSString *id,NSString *cityName);
@interface WLCCityListViewController : WLCBaseSquareViewController <UITableViewDataSource,UITableViewDelegate>
{   
    Block _block;
    id<commonDelegate>delegate;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil Block:(Block)block
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _block=block;
    }
    return self;
}        

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WLCMainViewCityListData *data=[[self citylists]objectAtIndex:[indexPath section]];
    //    [self.delegate seleteCityID:[[data.cityList objectAtIndex:indexPath.row]objectForKey:@"id"]  CityName:[[data.cityList objectAtIndex:indexPath.row]objectForKey:@"name"]];
    NSString *a1 =[[data.cityList objectAtIndex:indexPath.row]objectForKey:@"id"];

    NSString *a2 =[[data.cityList objectAtIndex:indexPath.row]objectForKey:@"name"];
    _block(a1,a2);    
}

Bクラス:

@interface WLCMainViewController : WLCBaseSquareViewController
{
}
@implementation WLCMainViewController

-(void)viewDidLoad {
    WLCCityListViewController *tableViewController = [[[WLCCityListViewController alloc]initWithNibName:@"WLCCityListViewController" bundle:nil Block:^(NSString *id, NSString *cityName) {
        self.cityID=id;
        WLCMainViewModel *model=(WLCMainViewModel *)self.mainviewModel;
        model.cityID=id;
        [model sendRequest];
        [self.view startWaiting];
    }] autorelease];
}
4

2 に答える 2

0

ブロックを OC オブジェクトと見なすことができます。
通常、ブロックを保持する必要がある場合は、Block_copy を使用して保持し、忘れずに Block_release を使用してください。
コードの問題は、呼び出し時にブロックが自動解放されることです。

于 2013-11-22T09:35:39.373 に答える
0
_block = block;

この行はクラッシュします。ブロックを割り当てるだけで保持しません。保持は使用せず、コピーのみを使用してください。コピー プロパティを宣言します。

@property (nonatomic, copy) Block _block;

セッターを使用します。または、このようにコードを変更してください。

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil Block:  (Block)block
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    //_block=block;
    _block = block? [[block copy] autorelease]: nil;
}
return self;

}

于 2012-10-11T03:56:25.360 に答える