if (!cell) {
cell = [[AddressTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:addressIdentifier];
}
為什麼要加個判斷,寫這個,什麼時候會走這個判斷
怪我咯2017-05-02 09:27:41
不判斷的話,每次就會創造一個新的,因為你這裡有個alloc
。
一般在這程式碼之前還有一行:
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
這行就是取復用的cell的,如果能取到的話,cell就有內存,可以直接復用,取不到的話,就要自己創建了,也就是你貼出來的代碼。
除此之外,也可以使用註冊的方式:
-(void)registerNib:(nullable UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);
-(void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);
註冊的話,就不需要去判斷了。一般來說,這麼用:
[self.tableView registerNib:[UINib nibWithNibClass:className] forCellReuseIdentifier:reuseId];
//或者
[self.tableView registerClass:className forCellReuseIdentifier:reuseId];
那麼,tableView:cellForRowAtIndexPath:
方法就不需要再加判斷了,可以直接取:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SomeIdentifier"];
//do something
...