Xcode from scratch for scaredy cats: Sending a message to a method (NSLog)

Last time we saw how to set up a subclass and reuse the object. This time we're going to send a message to a method contained in a subclass and the subclass will vary its output based upon the variable contained within that message.

I'm keeping things brief, and you'll need to recreate the 'New Project' and 'New File' elements by looking back at last time. This time, however, we'll make the new file a subclass of NSObject instead of UIView. This will mean we don't have "drawRect:" waiting for us to uncomment. So instead here is what your method looks like inside the subclass .m file:
- (void)performOperation:(NSString *)operation {
if ([(NSString *)operation isEqual:@"can you hear me?"]) {
NSLog(@"Yes I can hear you!");
}
else {
NSLog(@"nope!");
}}
And because this is a public method we'll need to add it to the .h file of the subclass with this line of code:
- (void)performOperation:(NSString *)operation;
so that the .h file of the subclass file looks like this:
#import <Foundation/Foundation.h>

@interface SendToMethod : NSObject
{
}

- (void)performOperation:(NSString *)operation;

@end

You'll notice the use of NSLog, which is one of the simplest ways in which we can test our apps in Xcode, and we'll see how this works in a moment. First, here is how we send a message containing the variable to the method from a ViewController.m file:
SendToMethod *newSend = [[SendToMethod alloc] init];
[newSend performOperation:@"can you hear me?"];
Like last time we can place this code within the viewDidLoad{} method. Remember to import the .h file of your subclass, like we did last time too, into your ViewController.m file.

Now run the app. At the bottom of the Xcode window (not the iPad/iPhone Simulator) a tiny arrow should turn blue. Press this arrow and you'll see the console. There you should find the answer to your message.

Now try changing the message being sent from the ViewController.m file and see if you receive the alternative response.

A quick breakdown of what has happened here:

  1. we've sent an NSString to the method 'performOperation:'
  2. since the method begins with (void) this tells us that it returns nothing, and so there is nothing else for our View Controller to do once the instance variable has been sent
  3. the method tells us that the variable should be of the type NSString, since it knows what to do with one of these
  4. once the NSString is received, then "operation" (within the method) is equal to the string we've sent, in this case "can you hear me?" (Note: the @ sign that precedes it is required and notifies the system it is a string.)
This has been a rather "sketchy" post, but I hope that there is enough detail here for you to follow the example, and if you are hazy about how to do any of this just return to earlier posts in the 'Xcode from scratch for scaredy cats' series to refamiliarize yourself.

Comments