views:

56

answers:

2

I was expecting this to work, only thinking it would fail if I had locally declared another variable called "tableView"

NSLog(@"X: %@", [tableView delegate]); // Fails: tableView undeclared

.

NSLog(@"X: %@", [[self tableView] delegate]); // Works:

Is this because you need self to refer to items on the actual object?

NB: this code is inside a UITableViewController, so delegate is a property on the UITableView.

+3  A: 

That's because the first option is attempting to access a variable or instance variable called tableView, which doesn't exist. (You can verify this by going to the File menu, choosing "Open Quickly", and typing "UITableViewController.h". You'll see that a UITableViewController does not have a tableView ivar)

The second one is accessing the tableview through the method -tableView, which is the approved way of getting to it.

Incidentally, if this is a UITableViewController subclass, then [[self tableView] delegate] should just be self (but I'm assuming you knew that).

Dave DeLong
Thanks Dave, very helpful. Yes I did know that it returned self, I was just using it as an example, again many thanks for your time and help.
fuzzygoat
+3  A: 

There is a difference between an instance variable in an object versus a property (@property syntax in ObjC).

When you say

[tableView delegate]

you are referring to an instance variable called 'tableView' which actually doesn't exist. Generally instance variables in UIKit start with underscore, the message being that you shouldn't use them directly.

On the other hand:

[[self tableView] whatever...] //OR
[self.tableView whatever]

refers to a property on UITableView called 'tableView'. That does exist. And it is the property that is the documented way to access that view, so that's really how you want to access it.

Hope that helps.

EDIT: ooops, too slow again! The previous answer is the same.

Firoze Lafeer
Thank you Firoze, much appreciated.
fuzzygoat