user2553675
user2553675

Reputation: 535

What does the following code means? Why here is used "id"?

UITableView *tableView = (id)[self.view viewWithTag:1]; //why id is used here?

[tableView registerClass:[BIDNameAndColorCell class] forCellReuseIdentifier:CellTableIdentifier];

This is a piece of code from the book "Beginning iOS 6 development", chapter 8, p.245.

I would like to know why here "id" is necessary?

Upvotes: 0

Views: 85

Answers (2)

Christian
Christian

Reputation: 1714

id is not necessary here, and I don't think it is a good idea. viewWithTag: returns a UIView object, but the code needs to know about the UITableView methods.

By casting to id (which is a pointer to any Objective-C object), the compiler allows any method to be sent to the tableView. This could cause problems though, if you try to send it a message that the UITableView doesn't know about.

It would be better to cast it to a UITableView object instead. This would be (UITableView *)[self.view viewWithTag:1];

Upvotes: 0

rmaddy
rmaddy

Reputation: 318814

id shouldn't be there. It should be:

UITableView *tableView = (UITableView *)[self.view viewWithTag:1];

The part in parentheses is called a "cast". This is needed because the viewWithTag: method returns a UIView reference but you wish to assign it to a UITableView variable. The cast tells the compiler that you know better and the returned view really is a table view. Without the cast the compiler will complain about an invalid assignment.

Using id also works here because id is a general type that can represent any object type.

Upvotes: 4

Related Questions