Reputation: 1453
I am having a hard time understanding how a particular code works so I went ahead and added the line
NSLog(@"%@ - %@", [self class], NSStringFromSelector(_cmd));
at the start of every method in the hope that I will be able to see the exact sequence in which the various methods are invoked along with their class names.
However, at times [self class]
is returning the name of a class in which the method is not actually present. For example, it shows the following in debug console -
PhotographersTableViewController - shouldAutorotateToInterfaceOrientation:, whereas, the method shouldAutorotateToInterfaceOrientation
is actually present in CoreDataTableViewController
.
How can this happen?
P.S. Also, is there a way in Xcode to add a line in all the methods of a file?
Upvotes: 0
Views: 119
Reputation: 53000
This is due to inheritance, which is fundamental to the way in which Obj-C, and most object-oriented programming languages, work. Glossing over details, this is how it works:
In all probability you have a declaration in your code like:
@interface PhotographersTableViewController : CoreDataTableViewController { ... }
This declares PhotographersTableViewController
as an extension of CoreDataTableViewController
- PhotographersTableViewController
is said to inherit the methods of CoreDataTableViewController
.
When you a method call:
PhotographersTableViewController *myPhotoView;
...
[myPhotoView shouldAutorotateToInterfaceOrientation];
Then Obj-C first looks for the method shouldAutorotateToInterfaceOrientation
in class PhotographersTableViewController
, which fails, and then in class CoreDataTableViewController
, which succeeds - so it invokes the method defined in CoreDataTableViewController
passing it the current object, i.e. the one referenced by the variable myPhotoView
, as the value of the self
argument (self
is just an argument to the method supplied automatically by Obj-C).
This process is fundamental to inheritance and Obj-C.
Therefore when you print out the value of self
you see the original object type.
The above glosses over a lot of detail, much of it very important: no mention of instance variables, hiding, scope, etc., etc. If you're learning Obj-C and object-oriented programming together you need to find a good book and read up on the details.
Upvotes: 4
Reputation: 21805
Self is an instance that is accessing the current method.. And for the other ques.. I don't think there is such an option to put certain line in every method... You can try code snippets though
Upvotes: 0
Reputation: 26952
If PhotographersTableViewController extends CoreDataTableViewController, then self is PhotographersTableViewController, even though the method exists in CoreDataTableViewController.
Upvotes: 0