ZeroChow
ZeroChow

Reputation: 442

CellForRowAtIndexPath in swift and Objective-C

When I traverse all the cell in a tableView, In Objective-C:

for (int i = 0; i < [_tableView numberOfRowsInSection:0]; i++) {
    UITableViewCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
    cell.textLabel.text = @"change text";
}

It worked, but in swift I code :

for index in 0...tableView.numberOfRowsInSection(0) {
        let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0))!
        cell.textLabel?.text = "\(index)"
    }

It crashed, and throws an unwrap nil error. It seems that can only get the visible cells in Swift and can get all cells in Objective-C. How to explain this?

Upvotes: 1

Views: 387

Answers (2)

Tim Vermeulen
Tim Vermeulen

Reputation: 12562

cellForRowAtIndexPath will only return the cell if it's currently visible, that's why your code causes a crash. To loop through all visible cells, just use

for cell in tableView.visibleCells {
    // do something
}

Upvotes: 2

Pradeep K
Pradeep K

Reputation: 3661

The behaviour is the same. Its just that in Objective C using a nil object does not crash whereas in Swift it crashes.

You can verify this by checking if the cell is nil or not in Objective-C and putting a log. In Swift to avoid the crash use optional binding instead.

E.g. if let cell = tableView.cellFor....

Upvotes: 4

Related Questions