May 27, 2014

Fast food objective-c (part 1) : Calling Methods

Objective-C is the primary language used to write Mac software. If you're comfortable with basic object-oriented concepts and the C language, Objective-C will make a lot of sense. If you don't know C, you should read the C Tutorial first. 
This tutorial is written and illustrated by Scott Stevenson.

Calling Methods

To get started as quickly as possible, let's look at some simple examples. The basic syntax for calling a method on an object is this:
[object method];
[object
methodWithInput:input];
Methods can return a value:
output = [object methodWithOutput];
output = [object
methodWithInputAndOutput:input];
You can call methods on classes too, which is how you create objects. In the example below, we call the string method on the NSString class, which returns a new NSString object:
id myObject = [NSString string];
The id type means that the myObject variable can refer to any kind of object, so the actual class and the methods it implements aren't known when you compile the app. 
In this example, it's obvious the object type will be an NSString, so we can change the type:
NSString* myString = [NSString string];
This is now an NSString variable, so the compiler will warn us if we try to use a method on this object which NSString doesn't support. 
Notice that there's a asterisk to the right of the object type. All Objective-C object variables are pointers types. The id type is predefined as a pointer type, so there's no need to add the asterisk.

Nested Messages

In many languages, nested method or function calls look like this:
function1 ( function2() );
The result of function2 is passed as input to function1. In Objective-C, nested messages look like this:
[NSString stringWithFormat:[prefs format]];
Avoid nested nesting more than two message calls on a single line, as it easily gets unreadable.

Multi-Input Methods

Some methods take multiple input values. In Objective-C, a method name can be split up into several segments. In the header, a multi-input method looks like this:
-(BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
You call the method like this:
BOOL result = [myData writeToFile:@"/tmp/log.txt" atomically:NO];


These are not just named arguments. The method name is actually writeToFile:atomically: in the runtime system.​

No comments:

Post a Comment