Objective-C iOS9泛型

Objective-C中,Array裏面放的默認是id類型,沒法直接使用點語法,那麼經過泛型對Array內的元素類型作約束,就能夠直接使用點語法了.swift

給數組添加類型約束以後,若是添加的內容類型不同,會報警告.數組

經過泛型的約束,Array使用快捷遍歷方式的時候,會直接帶出元素的類型.性能

舉個🌰  :atom

/*******************************************不加限制的數組*******************************************/

@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裏目前最經常使用的地方仍是限制集合元素類型spa

相關文章
相關標籤/搜索