Table of Contents Previous Section
Methods
To define a new method, simply put its implementation in the script file. You don't need to declare it ahead of time. For example:
- recordMe {Methods can take arguments. To define a method that takes arguments, you place the argument name after a colon (:). For example, the following method takes two arguments. It adds the two arguments together and returns the result:
if ([aName length]) {
[[self application] setLastVisitor:aName];
[self setAName:@""]; // clear the text field
}
}
- addFirstValue:firstValue toSecondValue:secondValue {The strings that appear to the left of the colons are part of the method name. The method above is named addFirstValue:toSecondValue:. It takes two arguments, which it calls firstValue and secondValue.
id result;
result = firstValue + secondValue;
return result;
}
If you want, you can add type information for the return values and parameter values. For example, the following method, subtractFirstValue:fromSecondValue:, subtracts one number from another and returns the result:
- (NSNumber *)subtractFirstValue:(NSNumber *)firstValue fromSecondValue:(NSNumber *)secondValue {In these examples, note that type information is optional. When there is no type, id is assumed. Also note that both example methods return a value, stored in result. If a method doesn't return a meaningful value, you don't have to include a return statement (a return value of nil is returned for methods without an explicit return statement).
NSNumber *result;
result = secondValue - firstValue;
return result;
}
Table of Contents Next Section