Objective-C iOS9泛型

Objective-C中,Array里面放的默认是id类型,无法直接使用点语法,那么通过泛型对Array内的元素类型做约束,就可以直接使用点语法了.

给数组添加类型约束之后,如果添加的内容类型不一样,会报警告.

通过泛型的约束,Array使用快捷遍历方式的时候,会直接带出元素的类型.

举个🌰  :

/*******************************************不加限制的数组*******************************************/

@property (nonatomic, strong) NSMutableArray *dataSource; //那么使用enum遍历的时候 [self.dataSource enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { //无法使用点语法,需要进行一次类型转化 NSString *storeId = [(YJCOrderModel *)obj store_id];
}];

//
这是代码中的一个表的数据源,哈哈偷懒了 @property (nonatomic, strong) NSMutableArray <YJCOrderModel *>*dataSource; //那么使用enum遍历的时候 [self.dataSource enumerateObjectsUsingBlock:^(YJCOrderModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { //直接带出了元素类型,其实也就是少写了一次强转而已哈哈 NSString *storeId = obj.store_id; //此处说一下,对于集合的遍历,做完想做的操作之后,如果可以的话,尽量把循环停止掉,毕竟小小的循环也是有性能消耗的哈哈 *stop = YES; }]; //表中使用的时候就可以直接取出Array内的固定类型了 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { YJCMyOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if (!cell) { cell = [[YJCMyOrderCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; } cell.status = YJC_MYORDER_CELL_ORDER_STATUS_NOTRECEIVE; cell.model = self.dataSource[indexPath.section]; YJCWeakSelf cell.cancelOrderBlock = ^(KDBMyOrderCell *cell){ [weakSelf cancelOrderWith:cell]; }; cell.againPrintBlock = ^(KDBMyOrderCell *cell){ [weakSelf againPrintWith:cell]; }; return cell; }

//哈哈说了这么多,真正用泛型的还是swift啊,OC里目前最常用的地方还是限制集合元素类型

posted on 2018-02-05 09:37  咿呀呀呀呀咿  阅读(111)  评论(0编辑  收藏  举报

导航