Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (24.65 MB, 900 trang )
sendEmailTo("somebody@somewhere.com",
"My Subject",
"Please read my email");
Turning this procedure into a function that returns a Boolean value, we will have code
similar to this:
BOOL sendEmailTo(const char *paramTo,
const char *paramSubject,
const char *paramEmailMessage){
/* send the email here ... */
if (paramTo == nil ||
paramSubject == nil ||
paramEmailMessage == nil){
/* One or some of the parameters are nil */
NSLog(@"Nil parameter(s) is/are provided.");
return NO;
}
}
return YES;
Calling this function is similar to calling the sendEmailTo procedure except that with a
function, we can retrieve the return value, like so:
BOOL isSuccessful = sendEmailTo("somebody@somewhere.com",
"My Subject",
"Please read my email");
if (isSuccessful){
/* Successfully sent the email */
} else {
/* Failed to send the email. Perhaps we should display
an error message to the user */
}
In Objective-C, each method is created for a class. Creating Objective-C methods is
quite different from writing procedures and functions in a programming language such
as C. Methods fall into two categories: instance or class. Instance methods are methods
that can be called on an instance of the class (that is, on each object you create based
on the class), whereas class methods get called on the class itself and do not require an
instance of the class to be created by the programmer. To create a method in ObjectiveC, follow these steps in the .m file of your target class:
1. Type − if you want an instance method or + if you want a class method.
2. Choose the return type of your method and enclose it within parentheses—for
instance, (void) for no return value, (BOOL) for a Boolean value, (NSObject *) to
return an instance of NSObject, and so on.
1.12 Defining Functionality for Classes | 43
www.it-ebooks.info
3. Choose a name for your method. Start the name with a lowercase letter. It is common in Objective-C to start method names with a lowercase letter—for instance,
sendEmailTo instead of SendEmailTo.
4. If you do not want any parameters for your method, jump to step 9.
5. Choose two names for your parameter. One name becomes a part of the method
name and will be used from outside the method (this is optional for all parameters
except the first). The other name will be used as a parameter name inside the
method. There is an exception to this in which the first name of the first parameter
of a method is part of the name of the method that you chose in step 3. For this
first parameter, you must only choose a second name, which becomes the parameter name used inside the method itself.
6. Once you are done choosing the name for your parameter, choose the data type of
the method and enclose it within parentheses.
7. Put a colon after your parameter’s first chosen name (if any), and put the parentheses that carry the data type of your method followed by the second name for
your parameter.
8. Repeat steps 5 through 7 for any other parameters that you might have.
9. Insert an open curly brace ({) after the method name and parameter names (if you
have parameters) and a closing curly brace (}) at the end.
Going back to the sendEmailTo procedure example that we saw earlier, let’s attempt to
create the same procedure as a method in Objective-C:
- (BOOL) sendEmailTo:(NSString *)paramTo
withSubject:(NSString *)paramSubject
andEmailMessage:(NSString *)paramEmailMessage{
/* Send the email and return an appropriate value */
if ([paramTo length] == 0 ||
[paramSubject length] == 0 ||
[paramEmailMessage length] == 0){
/* One or some of the parameters are empty */
NSLog(@"Empty parameter(s) is/are provided.");
return NO;
}
return YES;
}
This is an instance method (-) that returns a Boolean value (BOOL). The name of this
method is sendEmailTo:withSubject:andEmailMessage: and it has three parameters. We
can then call this method in this way:
[self sendEmailTo:@"someone@somewhere.com"
withSubject:@"My Subject"
andEmailMessage:@"Please read my email."];
44 | Chapter 1: The Basics
www.it-ebooks.info
As mentioned previously, the first name of every parameter (except the first) is optional.
In other words, we can construct the sendEmailTo:withSubject:andEmailMessage:
method in another way with a different name:
- (BOOL) sendEmailTo:(NSString *)paramTo
:(NSString *)paramSubject
:(NSString *)paramEmailMessage{
/* Send the email and return an appropriate value */
if (paramTo length] == 0 ||
[paramSubject length] == 0 ||
[paramEmailMessage length] == 0){
NSLog(@"Empty parameter(s) is/are provided.");
return NO;
}
return YES;
}
I heavily discourage you from writing methods that have no external
names for their parameters. This is indeed a very bad programming
practice and will confuse you and those who you work with in the same
team, regardless of how well you might have documented your code.
We can call this method like so:
[self sendEmailTo:@"someone@somewhere.com"
:@"My Subject"
:@"Please read my email."];
As you can see, the first implementation is easier to understand when you look at the
invocation, since you can see the name of each parameter in the call itself.
Declaring and implementing a class method is similar to declaring and implementing
an instance method. Here are a couple of things you have to keep in mind when declaring and implementing a class method:
• The method type identifier of a class method is + instead of the - type identifier for
instance methods.
• You can access self in a class method. However, the class methods of self can be
accessed only inside a class method’s implementation.
• Class methods are useful when you want to provide new methods of instantiation
for your classes. For example, a class method named allocAndInit could both allocate and initialize an object and return the object to its caller.
1.12 Defining Functionality for Classes | 45
www.it-ebooks.info
1.13 Defining Two or More Methods with the Same Name
Problem
You would like to implement two or more methods with the same name in one object.
In object-oriented programming, this is called method overloading. However, in
Objective-C, method overloading does not exist in the same way as it does in other
programming languages such as C++.
The techniques used and explained in this recipe’s Solution and Discussion are merely ways to create methods that have different numbers
of parameters or have parameters with different names, just to give you
an idea of how you can have methods whose first name segments are
the same.
Solution
Use the same name for your method, but keep the number and/or the names of your
parameters different in every method:
- (void) drawRectangle{
[self drawRectangleInRect:CGRectMake(0.0f, 0.0f, 4.0f, 4.0f)];
}
- (void) drawRectangleInRect:(CGRect)paramInRect{
[self drawRectangleInRect:paramInRect
withColor:[UIColor blueColor]];
}
- (void) drawRectangleInRect:(CGRect)paramInRect
withColor:(UIColor*)paramColor{
[self drawRectangleInRect:paramInRect
withColor:paramColor
andFilled:YES];
}
- (void) drawRectangleInRect:(CGRect)paramInRect
withColor:(UIColor*)paramColor
andFilled:(BOOL)paramFilled{
/* Draw the rectangle here */
}
46 | Chapter 1: The Basics
www.it-ebooks.info
This example shows a typical pattern in overloading. Each rectangle can be drawed
either filled (solid color) or empty (showing just its boundaries). The first procedure is
a "convenience procedure" that allows the caller to avoid specifying how to fill the
rectangle. In our implementation of the first procedure, we merely call the second procedure, making the choice for the caller (andFilled:YES) The second procedure gives
the caller control over filling.
Discussion
Method overloading is a programming language feature supported by Objective-C,
C++, Java, and a few other languages. Using this feature, programmers can create
different methods with the same name, in the same object. However, method overloading in Objective-C differs from that which can be used in C++. For instance, in
C++, to overload a method, the programmer needs to assign a different number of
parameters to the same method and/or change a parameter’s data type.
In Objective-C, however, you simply change the name of at least one parameter.
Changing the type of parameters will not work:
- (void) method1:(NSInteger)param1{
/* We have one parameter only */
}
- (void) method1:(NSString *)param1{
/* This will not compile as we already have a
method called [method1] with one parameter */
}
Changing the return value of these methods will not work either:
- (int) method1:(NSInteger)param1{
/* We have one parameter only */
return param1;
}
- (NSString *) method1:(NSString *)param1{
/* This will not compile as we already have a
method called [method1] with one parameter */
return param1;
}
As a result, you need to change the number of parameters or the name of (at least) one
parameter that each method accepts. Here is an example where we have changed the
number of parameters:
1.13 Defining Two or More Methods with the Same Name | 47
www.it-ebooks.info