Graphics Programs Reference
In-Depth Information
Now, whenever the button overlaid on the thumbnail is tapped,
ItemsViewControl-
ler
will be sent
showImage:atIndexPath:
. The first argument is a pointer to the
button that sent the original
showImage:
message, and the second argument is the
NSIndexPath
of the cell that this button is on. At least that is what should happen. Un-
fortunately,
HomepwnerItemCell
doesn't know the details of
ItemsViewCon-
troller
. Thus, it doesn't know that
ItemsViewController
implements
showImage:atIndexPath:
, and this code will generate an error.
One approach would be to import
ItemsViewController.h
into
Homepwner-
ItemCell.m
. However, this creates a dependency between
HomepwnerItemCell
and
ItemsViewController
and
HomepwnerItemCell
could not be used with any
other view controller. Let's take a different approach that will keep the two classes separ-
ate and give us some flexibility down the road.
Objective-C selector magic
We can use the flexible power of Objective-C's runtime messaging to generalize the im-
plementation of
showImage:
. Instead of explicitly sending
showImage:atIndexPath:
to the controller when
showImage:
is called, we are
going to send the message
performSelector:withObject:withObject:
. This
method takes a
SEL
that is the selector of the message to be sent, and the next two argu-
ments are the arguments to be passed in that message (in order). The controller then
searches for the method whose name matches the passed-in selector and executes it.
This is an interesting way of doing things, but we'll see why it is useful in a moment.
First, remember that a selector is just the name of a message. You can turn a selector into
a string, and you can turn a string back into a selector. In between these two steps, you can
modify the string that becomes the selector. This is what you will do for
Homepwner-
ItemCell
- when it is sent the message
showImage:
, it will get that selector, append
atIndexPath:
to it, and send the new selector to its controller in
performSelect-
or:withObject:withObject:
. The two arguments will be the sender of
showImage:
and the cell's index path.
In
HomepwnerItemCell.m
, modify the implementation of
showImage:
to construct
the selector and send this information to the controller.
- (IBAction)showImage:(id)sender
{
// Get this name of this method, "showImage:"