加载UITableView时,我一直在崩溃。我正在尝试使用nib文件中定义的单元格。
我在视图控制器头文件中定义了一个IBOutlet:
UITableViewCell *jobCell;
@property (nonatomic, assign) IBOutlet UITableViewCell *jobCell;
这在实现文件中合成。
我在IB中创建了一个UITableViewCell,并将其标识符设置为JobCell。
这是cellForRowAtIndexPath方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"JobCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"JobsRootViewController" owner:self options:nil];
cell = jobCell;
self.jobCell = nil;
}
// Get this job
Job *job = [fetchedResultsController objectAtIndexPath:indexPath];
// Job title
UILabel *jobTitle;
jobTitle = (UILabel *)[cell viewWithTag:tagJobTitle];
jobTitle.text = job.title;
// Job due date
UILabel *dueDate;
dueDate = (UILabel *)[cell viewWithTag:tagJobDueDate];
dueDate.text = [self.dateFormatter stringFromDate:job.dueDate];
// Notes icon
UIImageView *notesImageView;
notesImageView = (UIImageView *)[cell viewWithTag:tagNotesImageView];
if ([job.notes length] > 0) {
// This job has a note attached to it - show the notes icon
notesImageView.hidden = NO;
}
else {
// Hide the notes icon
notesImageView.hidden = YES;
}
// Job completed button
// Return the cell
return cell;
}
当我运行应用程序时 - 我遇到了严重的崩溃,控制台会报告以下内容:
objc [1291]:FREED(id):发送给释放对象的消息样式= 0x4046400
我正确地连接了IB中的所有插座。有什么问题?
谢谢,
答案 0 :(得分:0)
你的问题出在这个街区:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"JobsRootViewController" owner:self options:nil];
cell = jobCell; <- THIS IS A SHALLOW COPY
self.jobCell = nil; <- YOU JUST RELEASED IT
}
// Get this job
Job *job = [fetchedResultsController objectAtIndexPath:indexPath];
// Job title
UILabel *jobTitle;
jobTitle = (UILabel *)[cell viewWithTag:tagJobTitle]; <- CELL ISNT THERE ANYMORE
您正在将jobCell创建为已分配的属性。当你说self.jobCell = nil时你使用的合成setter会释放你刚刚进行单元格引用的对象。改为进行深层复制,或者不将jobCell设置为nil。
答案 1 :(得分:0)
最简单的方法是将其分解为两个单独的nib文件,并从单元格自己的笔尖加载单元格。需要注意的是,你不能设置这样的出口,如果你想这样做,你需要一个自定义的UITableViewCell子类。但是如果你没有在单元格中连接任何东西,你可以简单地这样做:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"JobsRootViewCell" owner:nil options:nil] objectAtIndex:0];
}
答案 2 :(得分:0)
您应该注册xib文件,以便在tableView中使用它:
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "CellXibName", bundle: nil), forCellReuseIdentifier: "CellReuseIdentifier")
}
UITebleViewDataSource方法:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellReuseIdentifier", forIndexPath: indexPath) as! CellClass
return cell
}
<强>的TableView 强>
if let tableView: CustomTableView = nib?.first as? CustomTableView
{
self.view.addSubview(tableView)
}