编辑
消除performSelector导致的警告
本文访问次数:0

为了在IndexViewController中统一处理所有的事件(广告,商品,店铺等相关事件),需要在BannerCell中声明一个target和一个selector,用来在特定时刻make target perform this selector(用英文容易理解)

//BannerCell.h
@interface BannerCell : UICollectionViewCell
@property (nonatomic, strong) SwipeView* swipeView;
@property (nonatomic, assign) SEL selector;
@property (nonatomic, strong) id selectorTarget;
@end

在IndexViewController.m中对selectorTarget和selector进行赋值

//IndexViewController.m
- (void)setUpBannerCell:(UICollectionViewCell*)cell
                  model:(ResponseModelAppIndexDataModel*)dataModel
              indexPath:(NSIndexPath*)indexPath {
    BannerCell* bannerCell = (BannerCell*)cell;
    bannerCell.selectorTarget = self;
    [bannerCell.swipeView setPositionForTag:indexPath.row];
    [bannerCell.swipeView setViewTypeForTag:BANNER_CELL_ITEM];
    bannerCell.selector = @selector (buttonClicked:);
    [bannerCell setUpWithModel:dataModel];
}

如果使用以下代码调用的话,编译器会发出警告

//BannerCell.m
- (void)swipeView:(SwipeView*)swipeView didSelectItemAtIndex:(NSInteger)index {
    //performSelector may cause a leak because its selector is unknown
    [self.selectorTarget performSelector:self.selector withObject:nil afterDelay:0];
}

而采用以下方法调用的话就不会出现此警告

//BannerCell.m
- (void)swipeView:(SwipeView*)swipeView didSelectItemAtIndex:(NSInteger)index {
    if (!self.selectorTarget) {
        return;
    }
    if (![self.selectorTarget respondsToSelector:self.selector]) {
        return;
    }
    [swipeView setExtraInfoForTag:index];
    IMP imp = [self.selectorTarget methodForSelector:self.selector];
    //注意id对应SEL中的self变量
    void (*func) (id, SEL, UIView*) = (void*)imp;
    func (self.selectorTarget, self.selector, swipeView);
}

以下代码为selector对应的代码

//IndexViewController.m
- (void)buttonClicked:(UIButton*)sender {
    NSInteger buttonType = [sender getViewTypeOfTag];
    NSInteger position = [sender getPositionOfTag];
    NSInteger extraInfo = [sender getExtraInfoOfTag];
    switch (buttonType) {
    case GO_TO_TOP_BUTTON:
        [self.collectionView setContentOffset:CGPointMake (0, 0) animated:YES];
        break;
    case MESSAGE_BUTTON:
        [self openMessageViewController];
        break;
    case MENU_BUTTON:
        [self openMenuOfPosition:position extraInfo:extraInfo];
        break;
    case BANNER_CELL_ITEM:
        [self openAdOfPosition:position extraInfo:extraInfo];
        break;
    case ONE_COLUMN_AD_ITEM:
        [self openAdOfPosition:position extraInfo:extraInfo];
        break;
    default:
        NSLog (@"Button clicked,view type is %ld,position is %ld,extraInfo is %ld",
               (long)buttonType, (long)position, (long)extraInfo);
        break;
    }
}
没有任何评论