如何使用块替换常见委托

时间:2012-09-15 07:14:18

标签: ios delegates block

一堂课:

在以下方法中,我使用块来替换公共委托。好吗? 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];
}

2 个答案:

答案 0 :(得分:0)

_block = block;

此行导致崩溃。你只是分配一个块但不保留它。不使用保留,只使用副本。 声明一个复制属性。

@property (nonatomic, copy) Block _block;

并使用setter。或者只是改变你这样的代码。

- (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;

}

答案 1 :(得分:0)

您可以将块视为OC对象  通常,如果您需要保留块,请使用Block_copy执行此操作,并且不要忘记阻止它释放它 你的代码的问题是当你调用它时块是自动释放的。