Reputation: 812
I am new in iOS development. Currently I am reading this tutorial http://www.appcoda.com/how-to-handle-row-selection-in-uitableview/ . I am facing problem when I am reading this line
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
I know object in objective-c is created by following way
classname *objecname = [[classname alloc]init];
My confusion point is here UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
How cell
object is created here? Please tell details.
Upvotes: 1
Views: 8721
Reputation: 4257
Based on the tutorial you linked to, I'm assuming you are dealing with selecting a row. When you select a row, you have access to the NSIndexPath
of that row, which contains two parts:
With that information, let's break down the confusing code: UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UITableViewCell *cell
This part declares your variable. You've chosen to name it cell
. You could just as easily have named it theCell
, like so:
UITableViewCell *theCell
The *
means that you're declaring a pointer, which is just a reference to an actual object, or the table view cell.
[tableView cellForRowAtIndexPath:indexPath]
The tableView
refers to the UITableView
that was just selected. UITableView
has a method called cellForRowAtIndexPath
, and what that method does is retrieve the cell at the specified section and row of the UITableView
. In your case, it retrieves the row that you've just selected and stores the reference to it in your cell
variable.
When declaring a new object, yes, it would take on the following syntax:
classname *objecname = [[classname alloc] init];
The key word here is new
. When dealing with selecting rows in a UITableView
, you don't want to create a new cell because you can't select a cell that doesn't exist. You want to get the cell that the user has just selected.
Upvotes: 5
Reputation: 104082
The cell is not created with that line. That line gets a reference to a cell that is already in the table view at that indexPath.
Upvotes: 2
Reputation: 17622
I assume you have this code in your didSelectRowAtIndexPath:
method, is that right?
If so, you're tapping on a cell that is on the screen, so the cell object already exists. Where and how was it created? Inside cellForRowAtIndexPath:
, which you have already written.
So when you make this call
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
it just gives you the cell object to work with, but it doesn't create a new one.
Upvotes: 3