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 回答