This is the second post about IOS that I am writing out. You can read the first one over here.
In this post I am going to talk about Object-C object oriented principles, such as: classes, interfaces, instance variables and methods. This is an important topic in object-c, therefore I advice you to read this post carefully.
Interfaces
As you should know, Object-C is Object Oriented. In any OO language, we can use interface implicitly or explicitly.
In Object-C the interface is implemented in a separated file with extension .h (header) and lives together with a class. To create an interface/class in XCode, simply right mouse click on Classes folder -> Add -> New File. On the new window, select Object-C class and subclass NSObject:
.
XCode is going to create two files, an interface (.h) and the class (.m).
Let’s see an interface example:
1
2
3
4
5
6
7
8
9
10
| #import <Foundation/Foundation.h>
@interface Shape : NSObject {
@private
NSString *color;
CGPoint *position;
}
-(void)setColor:(NSString *)aColor;
-(void)drawShape;
@end |
Let’s study the code above.
First of all, the interface has the directive @interface and ONLY on it we can create inheritance. In the example above, our interface Shape inherits from NSObject.
Note: 1 – Other languages, such as Java and C#, the inheritance occurs in the class. In Object C, only the interface has inheritance. 2 – NSObject is the most common object from Cocoa Touch Framework.
In the interface, we have the #import statement. In our example, we imported the Foundation.h interface that belongs to Cocoa framework.
Another weird behavior: Instance variables can be only defined in the interface and inside the { } signs. In our example, there are two instance variables (color and position). Also, both instance variables have the private visibility, in other words, nobody can access these variables outside of this interface/class.
Finally, the method signature is defined outside the { } signs. Our example has two methods.
Class
A class, also known as implementation in object-c, has the extension .m. It implements all methods from its interface. See the example below:
1
2
3
4
5
6
7
8
9
| #import "Shape.h"
@implementation Shape
-(void)setColor:(NSString *)aColor {
color = aColor;
}
-(void)drawShape {
NSLog(@"Drawing a shape...");
}
@end |
The implementation has the @implementation directive and imports the interface through #import “Shape.h” line. Different from other languages, if you do not implement ALL methods on the class, there will not be a compiler error.
As you can see, the class does not have the { } signs and instance variables definitions. Also, there is no inheritance. All of this behaviors are implemented in the interface.
Instance Variables
As already said, instance variables are defined in the interface and within the { } signs. Another important point here is the pointer sign (*). ALL instance variables must be defined as a pointer. Also, all instance variables go to memory HEAP when created (we’ll see how it works in this post yet).
Within the { } signs we also define the visibility. By default, the visibility is protected, but in OO, usually we define the instance variables as private and we use some methods to access those variables. If you have no idea what private, protected or public are, please, google about Object Oriented Visibility.
Methods
Certainly it is the weirdest thing in this topic. We’ve already showed two methods examples:
1
2
| -(void)setColor:(NSString *)aColor;
-(void)drawShape; |
The first one receives a parameter and the second has no parameter. To define a parameter for a method, we use the following syntax: method name : (parameter type) parameter name; Weird? not so far, but what about multiples parameters? Let’s see another example from a war game:
1
| -(NSArray *)shipsAtPoint:(CGPoint *)bombLocation withDamage:(BOOL)damaged; |
What’s the method name? How many parameters do we have? Looks like method’s name and parameters are messed up, right?. Yes, that’s right, you put the parameters inside the method name and read it directly. Thus the method’s name above is shipsAtPointWithDamage and it has two parameters.
The most languages has the full method name and then the parameters split by comma, like example below in Java:
1
| public AnyObject[] shipsAtPointWithDamage(CGPoint point, Boolean damaged); |
What about four parameters?
1
2
3
4
| -(void)splitViewController:(UISplitViewController *) svc
willHideViewController:(UIViewController *) aViewController
withBarButtonItem:(UIBarButtonItem *) barButtonItem
forPopoverController:(UIPopoverController *) popoverController; |
Man, that’s really weird. Honestly, I did not get used with this syntax yet.
Finally, let’s talk about the minus sign.
Minus sign means that the methods are instance methods, in other words, it can access the instance variables. Plus means that the methods are class methods. It cannot access instance variables. Usually used for global methods. You do not need a class instance to access it (Similar, but not identical, to static in Java).
Instantiating a Class
Probably you already heard this phrase: Object is a class instantiated. But how can we instantiate a class in object-c?
Usually we use a couple of methods: alloc and init. See example below:
1
| shape = [[Shape alloc] init]; |
Do not worry about [ ] yet. Just see the alloc and init methods. To create an object, we must alloc it in the HEAP memory. It is done through the alloc message. Also, we need to initiate it. It is done through a method that starts with the first four letters “init”. It’s common see an init method called: initWithAnyValue…
Init works like constructor of languages such as Java and C#.
Sending message to a method
Unlike Java or plain C, Objective-C works with messages. You don’t invoke a method on an object, instead, you send a message to it (like the Ruby language). Supposing our example SHAPE, we have the object shape (it’s the receiver) and we want to send a message to it to draw something (remember, we’ve got a draw method).
[shape drawShape];
You send messages inside the brackets [ ].
What about the code below?
[shape transform]
We do not have the method transform, so we’ll get a compiler error, right? No, because we are not invoking a method to an object, we are sending a message to an object (or receiver). In this case, the message is “transform”, but we do not have the transform method, thus, the compiler will show up a warning, but not an error. (carefully with this behavior).
Hands on
Let’s create a simple example to practice the class creation, inheritance, instance variables and method. Actually, I’m not going to show up step-by-step, instead, I’m going to tell you what the exercise is and you’ll do it yourself alone (hopefully). In the end of this topic, there’s a link to download the exercise done. (Promise that you’ll download the exercise just for conference).
The exercise looks simple. First: create more two classes (Circle and Rectangle) that inherits from Shape. Both classes must implement the drawShape method and print out the string “Circle or Rectangle”, also, first print out the content of the drawShape from superclass. To print out a content, use the NSLog method like the drawShape example.
Note: To call a method in the superclass, send a message to it using [super drawShape];
Create an User Interface that has two buttons (Circle and Rectangle). Each on acts a different method on the Controller. The controller instantiates the Circle or Rectangle class and call the drawShape method.
To see the output of NSLog inside the Xcode, go to menu Run -> Console. A new window will be opened. Now, let’s get started.
Conclusion
Although there are many things to say about class, interface, instance variables and methods, I guess this topic is a good starting point. I advice you, look at Mac Developers site about these topics and read the official documentation carefully. Also, there’re many blogs on the web that talks about object-c.
The next topic we’re going to talk a little more about instance variables and methods. Actually, we’re going to talk about the @property and @synthesize directives. Also, we’re going to talk about another important concept: Dot Operation.
If you have any question, fell free to leave your comment below.
Download the exercise here.