iOS try-catch-finally初次使用

本文介绍了在SwiftUI中处理UITableViewCell加载XIB的问题,并提供了一种解决方案:通过try-catch块来判断是加载XIB还是使用代码加载,适用于不同的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#背景

今天在使用以前封装的tableHandle时发生了报错, 原因是tableHandle没有支持加载xib, 如下:公开方法

在实现中只支持代码:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    id item = [self itemAtIndexPath:indexPath];
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:self.aCellClassName];
    if (!cell) {
        cell = [(UITableViewCell *)[NSClassFromString(self.aCellClassName) alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:self.aCellClassName];
    };
    if (self.configureCellBlock) {
        self.configureCellBlock(indexPath, item, cell);
    }
    return cell;
}

#让工具类支持xib 3种思路:

1.文件工具检查工程是否有xib文件,没有则用代码加载(浪费了大量时间,最后也没有完美解决!_!)

2.在.h设置一个标志,需要时候加载xib,默认代码加载(线上使用的方法)

3.使用try-catch(忽然想到的,推荐) ###最终修改的代码

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    id item = [self itemAtIndexPath:indexPath];
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:self.aCellClassName];
    if (!cell) {
        @try {
            cell = [[[NSBundle mainBundle] loadNibNamed:self.aCellClassName owner:self options:nil]firstObject];
        } @catch (NSException *exception) {
            cell = [(UITableViewCell *)[NSClassFromString(self.aCellClassName) alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:self.aCellClassName];
        } @finally {
            
        }
    };
    if (self.configureCellBlock) {
        self.configureCellBlock(indexPath, item, cell);
    }
    return cell;
}

###ps:工具类的gitHub: https://github.com/poos/SXHelper ###iOS捕获异常,常用的异常处理方法 http://blog.youkuaiyun.com/u011417413/article/details/51536672

转载于:https://my.oschina.net/bieshixuan/blog/861532

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值