美文网首页
tableview 使用中防止数组越界

tableview 使用中防止数组越界

作者: 编程猫猫 | 来源:发表于2018-03-20 10:54 被阅读0次

    在写项目的时候,调用下面的方法时

    - (void)fetchOwnedStockSocketData
    {
        [self.ownedStockDataArray enumerateObjectsUsingBlock:^(DNUserOptionalListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       [self.secket dn_establishConnectionWithParams:obj.prod_code subscribeType:DNSocketMsgSendSubscribeTypeSubscribe successOnMainThread:^(NSDictionary * _Nullable data) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                    DNUserOptionalListModel *userOptionalEntity = self.ownedStockDataArray[indexPath.row];
                    if ([userOptionalEntity.last_px floatValue] != [data[@"last_px"] floatValue]) {
                        userOptionalEntity.last_px = data[@"last_px”];
                        userOptionalEntity.px_change_rate = data[@"px_change_rate”];
                        DLog(@"prod_code=====%@",data[@"prod_code”]);
                        if ([obj.prod_code isEqualToString:data[@"prod_code"]] && self.searchController.active == NO) {
                            [self.ownedStocktableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                        }
                    }
            }];
        }];
    }
    
    崩溃日志如下: 111.png

    其实这是数组越界造成的:解决方案如下

    - (void)fetchOwnedStockSocketData
    {
        [self.ownedStockDataArray enumerateObjectsUsingBlock:^(DNUserOptionalListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [self.secket dn_establishConnectionWithParams:obj.prod_code subscribeType:DNSocketMsgSendSubscribeTypeSubscribe successOnMainThread:^(NSDictionary * _Nullable data) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                if (indexPath.row <= self.ownedStockDataArray.count-1) {
                    DNUserOptionalListModel *userOptionalEntity = self.ownedStockDataArray[indexPath.row];
                    if ([userOptionalEntity.last_px floatValue] != [data[@"last_px"] floatValue]) {
                        userOptionalEntity.last_px = data[@"last_px"];
                        userOptionalEntity.px_change_rate = data[@"px_change_rate"];
                        DLog(@"prod_code=====%@",data[@"prod_code"]);
                        if ([obj.prod_code isEqualToString:data[@"prod_code"]] && self.searchController.active == NO) {
                            [self.ownedStocktableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                        }
                    }
                }
            }];
        }];
    }
    

    增加了防止数组越界的判断,这句代码

    if (indexPath.row < self.ownedStockDataArray.count) {
    }

    相关文章

      网友评论

          本文标题:tableview 使用中防止数组越界

          本文链接:https://www.haomeiwen.com/subject/lvbpqftx.html