A. Introducing Objective-C

To help those who are new to Objective-C—the language behind iOS and the one you’ll use when making games for the iPhone, this appendix provides a quick introduction and overview of that programming language

Objective-C dates back to the early 1980’s when it was primarily written by Brad Cox and Tom Love, and inspired by the Smalltalk language. Their intention was to include some of the object-oriented (OO) features of Smalltalk, while remaining backward-compatible with C. Objective-C is most often described as a superset of C.

When creating iOS apps, much of the OpenGL ES code you will write will intermingle standard C and Objective-C. In fact, because the OpenGL ES API is written in C, you will be calling OpenGL methods using C-style syntax.

Syntax Differences

The major difference between Objective-C and other object-oriented languages is the use of square brackets and named parameters.

For example, to call a method in C/C++ with parameters, your code might look like:

myObject.method(argument);

In Objective-C, the equivalent code would be:

[myObject method:argument];

This style of calling methods in Objective-C is called messaging because you send a message to an object, rather than calling a method on it. As seen in the previous example, messages take the form of:

[objectToSendMessageTo methodName]

If you are sending a message to the same object that is receiving it, then self is used:

[self methodName]

Header Implementation Files

Like standard C, Objective-C has header and implementation files. Typically, these end with .h and .m. The header file (or interface file in Objective-C parlance) usually contains definitions for instance variables, properties, and methods. A header file comprises the following parts:

Import Declarations

Any external files or classes to be used in your class must be imported using @import or @class.

@import uses code contained in the file it refers to; whereas @class tells the compiler that the header file will use code contained in that file, but that it will be imported elsewhere—usually in the corresponding .m file. An example is:

#import <UIKit/UIKit.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
@class EAGLContext;

@interface declaration

The interface declares the name of the class, and any class that it might inherit from, for example:

@interface myclass : superclass

Instance variables are then declared between a set of braces, for example:

{
    NSInteger myInteger;
    NSString *highScore;
}

After that, any properties or methods are defined, and the file is ended with an @end declaration. An example header file might look like:

#import <UIKit/UIKit.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
@class EAGLContext;
@interface MyClass : NSObject
{
    GLint framebufferWidth;
    GLint framebufferHeight;
}
@property (nonatomic, retain) EAGLContext *context;
- (void)setFramebuffer;
- (BOOL)presentFramebuffer;
@end

Implementation File

The implementation file is where the magic happens. Implementation files are usually suffixed with .m, which originally signified “messages.” Much like the header file, the implementation file starts with #import declarations and the code starts with an @implementation declaration and ends with an @end statement. An example implementation file might look like this:

@implementation EAGLView
@synthesize context;
- (void)setContext:(EAGLContext *)newContext
{
    if (context != newContext) {
        [self deleteFramebuffer];
        [context release];
        context = [newContext retain];
        [EAGLContext setCurrentContext:nil];
    }
}
@end

Under the implementation declaration is an @synthesize command which is a “compiler cheat” that was introduced in Objective-C 2.0.

With any property, the compiler will generate the appropriate getter and setter methods. Prior to 2.0, the developer had to do a lot more coding to create the same result. It’s beyond the scope of this book to detail the specifics of this command, but you will see many examples of it in the chapter code in this book.

The rest of the code should be readable to anyone who has programmed in another OO-based language.


Note

image

The example code used here has had other methods removed for space reasons. As a result, it is not functional and used only to illustrate how an implementation file might look.


Instantiating Objects

A class is worthless without being instantiated into an object. If these terms are not familiar, think of a class as a builder’s blueprints, and an object as the finished building.

You have two ways to instantiate a class in Objective-C. Some classes have methods that return an autoreleased object, which means that you don’t have to worry about allocating or releasing memory, the parent object will do that. For example, when dealing with strings, the built-in NSString class has a number of methods that return an autoreleased object, for example:

NSString *myString = [NSString stringWithString:@"Hello"];

The other way to instantiate an object is to call the alloc and init methods of the class. It is common practice in Objective-C to combine the methods into one statement. For example, to instantiate an empty NSString object:

NSString *myString = [[NSString alloc] init];

The only real difference with the latter approach is that now you have an initialized object, so you will have to release it when you’re finished with it. You’ll read more about that in the next section.

Memory Management

Memory management in iOS programming isn’t as simple as in some other languages, but it remains straightforward. You should remember two golden rules:

• If you create an object using alloc or copy, then you have to release it.

• If you didn’t create an object directly, then don’t release it.

Using the examples from the previous section, here’s an example of the first rule:

NSString *myString = [[NSString alloc] init];
...
[myString release];

And here’s an example of the second rule:

NSString *myString = [NSString stringWithString:@"Hello"];

Retain/Release

Objective-C maintains a mechanism called a retain count. When you alloc/init an object, it receives a retain count of 1. When you call release, it decrements the retain count. At first glance, it might seem strange to have this mechanism at all. In addition to release, objects can call autorelease, and the runtime will release the object sometime in the future. autorelease is used on short lifecycle objects, or when returning an object in a method. It is up to the calling code to retain the object if it will be needed for a longer term. This technique is called taking ownership, for example:

- (NSString *)stringFromNumber:(NSInteger)number {
    NSString *string = [[NSString alloc] init];
    return [[string stringByAppendingFormat:@"%i", number] autorelease];
}

This code creates an object using alloc/init, so the retain count becomes 1. It then returns the object and calls autorelease, giving the object a retain count of 0. However, the object has not yet been released by the autorelease pool.

To call the code you would use something like:

NSString *myString = [self stringFromNumber:1];

If myString above is to be used elsewhere, it is a good idea to take ownership of it, for example:

[myString retain];
// do some more coding in here
[myString release];

New to iOS 5: ARC

ARC stands for Automatic Reference Counting. It is an Objective-C feature that  is new to iOS 5. In a nutshell, ARC takes the jobs of retain/release and reference counting away from the developer and gives it to the compiler. It is important to be aware that ARC is not a garbage collector but a compiler feature. Because the LLVM compiler knows everything about your objects, it also knows when they should be retained and when they should be released. The number one source of bugs in iOS is memory errors, and ARC effectively removes most of those issues. ARC is backward-compatible with iOS 4.x, but you may need to upgrade your project, which is an option in Xcode 4.2. All of the code in this book uses ARC.

Protocols and Categories

If you come from another language, you already will be familiar with protocols and categories. A protocol is similar to an interface in other languages. It defines a set of contracts that a conforming class may adhere to. Categories are similar to extension methods in C# or mixins in Ruby and Python. A category extends the functionality of a class.

An example protocol:

@protocol Sprite <NSObject>
- (NSInteger)getWidth;
- (NSInteger)getHeight;
- (void)addImage:(UIImage *)image;
- (void)draw;
@end

To implement the protocol, you add the protocol name in the interface declaration:

@interface Player<Sprite>

While it might appear that protocols function the same as inheriting from a superclass, it is important to understand that they are different. Inheriting from another class means your new class is of type x, whereas if you use protocols, your class conforms to protocol x. You can also have many protocols in the same class, for example:

@interface Player<Sprite, GameObject>

An example of a category in action:

@interface NSString(AdditonalStringMethods)
- (NSString *)reverseString;
- (BOOL)isANumber(NSString *)source;
@end
@implementation NSString(AdditonalStringMethods)
- (NSString *)reverseString {
  // code goes here to reverse string
}
- (BOOL)isANumber(NSString *)source {
    //code goes here to check string is a number
}
@end

And to use the category, you could do something like:

NSString *string = @"Hello World";
NSString *reversedString = [string reverseString];

Wrapping Up

Let’s end this discussion of Objective-C by hitting the high points:

• Methods are called in the form of [object method]. If calling a method in the same class, you use self, for example, [self myMethod].

• Parameters are named, such as [self myMethod:myParameter].

• If you create the object, then you need to release it.

• Likewise, if you don’t create the object, then don’t release it.

• Categories and protocols offer powerful and useful functionality.

Objective-C involves much more than the elements explained in this overview. It is recommended that you do further reading of the Objective-C documents that Apple supplies on http://developer.apple.com, or browse the many introductory articles about Objective-C on the Internet.

Objective-C may look a little weird if you haven’t used it before; but in time you will appreciate its power and nuances, and it may end up being your favorite language.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.176.243