The most important difference is that the forIndexPath:
version asserts (crashes) if you didn't register a class or nib for the identifier. The older (non-forIndexPath:
) version returns nil
in that case.app
You register a class for an identifier by sending registerClass:forCellReuseIdentifier:
to the table view. You register a nib for an identifier by sending registerNib:forCellReuseIdentifier:
to the table view.ide
If you create your table view and your cell prototypes in a storyboard, the storyboard loader takes care of registering the cell prototypes that you defined in the storyboard.布局
Session 200 - What's New in Cocoa Touch from WWDC 2012 discusses the (then-new) forIndexPath:
version starting around 8m30s. It says that “you will always get an initialized cell” (without mentioning that it will crash if you didn't register a class or nib).this
The video also says that “it will be the right size for that index path”. Presumably this means that it will set the cell's size before returning it, by looking at the table view's own width and calling your delegate's tableView:heightForRowAtIndexPath:
method (if defined). This is why it needs the index path..net
UITableView中有两种重用Cell的方法:prototype
在iOS 6中dequeueReusableCellWithIdentifier:被dequeueReusableCellWithIdentifier:forIndexPath:所取代。如此一来,在表格视图中建立并添加UITableViewCell对象会变得更为精简而流畅。并且使用dequeueReusableCellWithIdentifier:forIndexPath:必定会返回cell,系统在默认没有cell可复用的时候会自动建立一个新的cell出来。code
使用dequeueReusableCellWithIdentifier:forIndexPath:的话,必须和下面的两个配套方法配合起来使用:对象
一、若是是用NIB自定义了一个Cell,那么就调用registerNib:forCellReuseIdentifier:blog
二、若是是用代码自定义了一个Cell,那么就调用registerClass:forCellReuseIdentifier:get
以上这两个方法能够在建立UITableView的时候进行调用。
这样在tableView:cellForRowAtIndexPath:方法中就能够省掉下面这些代码:
取而代之的是下面这句代码:
1、使用NIB
一、xib中指定cell的Class为自定义cell的类型(不是设置File's Owner的Class)
二、调用registerNib:forCellReuseIdentifier:向数据源注册cell
三、在tableView:cellForRowAtIndexPath:中使用dequeueReusableCellWithIdentifier:forIndexPath:获取重用的cell,若是没有重用的cell,将自动使用提供的nib文件建立cell并返回(若是使用dequeueReusableCellWithIdentifier:须要判断返回的是否为空)
四、获取cell时若是没有可重用cell,将建立新的cell并调用其中的awakeFromNib方法
2、不使用NIB
一、重写自定义cell的initWithStyle:withReuseableCellIdentifier:方法进行布局
二、注册cell
三、在tableView:cellForRowAtIndexPath:中使用dequeueReusableCellWithIdentifier:forIndexPath:获取重用的cell,若是没有重用的cell,将自动使用提供的class类建立cell并返回
转自:
http://stackoverflow.com/questions/25826383/when-to-use-dequeuereusablecellwithidentifier-vs-dequeuereusablecellwithidentifi
http://eric-gao.iteye.com/blog/2234047