1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Kỹ thuật lập trình >

1  Implementing and Using Custom Objects

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 (8.37 MB, 640 trang )


Figure 1-1. The New File dialog



After you click Finish, Xcode will create the new class in the currently selected location

in the project hierarchy:

#import

@interface MyObject : NSObject {

}

@end



As you can see, the MyObject object inside the MyObject class file inherits from

NSObject. Now you can import this class into your other class files and instantiate an

object of type MyObject:

#import "ObjectsAppDelegate.h"

#import "MyObject.h"

@implementation ObjectsAppDelegate

@synthesize window;



1.1 Implementing and Using Custom Objects | 3



www.it-ebooks.info



- (BOOL)

application:(UIApplication *)application

didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

MyObject *someObject = [[MyObject alloc] init];

/* Do something with the object, call some methods, etc. */

[someObject release];

[window makeKeyAndVisible];

}



return YES;



- (void)dealloc {

[window release];

[super dealloc];

}

@end



Figure 1-2. Choosing a name for the class that is to be created



4 | Chapter 1: Working with Objects



www.it-ebooks.info



I am a big supporter of writing reusable code. In other words, I try to avoid writing the

same line of code twice, if possible. Sometimes you have to write code here and there

that feels like repeated code. But if you believe a block of code can be reused, you can

put it in an object and keep it in a separate project. After you have built up a library of

reusable code, you will want to, at some point, reuse that code in your new projects.

In such cases, it’s best to keep your reusable code in one place and refer to it in your

Xcode project instead of duplicating that code by copying it into your new project.

To reuse that code, you can create a new group in Xcode by right-clicking on your

project in Xcode and choosing Add→New Group, as shown in Figure 1-3. You can then

give this new virtual folder or group a name, such as “Shared Libraries” or “Shared

Code.” Once you are done, locate your reusable code in the Finder and drag and drop

it into the Shared Libraries group in Xcode. This way, Xcode will create the required

paths so that you can instantiate new objects of your reusable classes.



Figure 1-3. Creating a new group or virtual folder in Xcode



Creating a new group does not create the corresponding folder in the

filesystem.



See Also

Recipe 1.6; Recipe 1.7



1.1 Implementing and Using Custom Objects | 5



www.it-ebooks.info



1.2 Allocating and Initializing Objects

Problem

You want to create an instance of a new object, but you don’t understand the difference

between allocation and initialization and why you should have to both allocate and

initialize an object before you can use it.



Solution

You must both allocate and initialize an object before using it. An object must be allocated using the alloc instance method. This class method will allocate memory to

hold the object and its instance variables and methods. Each object must have one

designated initializer, which is normally the initialization method with the most parameters. For instance, the initWithFrame: method is the designated initializer of

objects of type UIView. Always allocate and initialize your objects, in that order, before

using them.

When implementing a new object, do not override the alloc method. This method is

declared in NSObject. Instead, override the init method and create custom initialization

methods that handle required parameters for the specific object you are working on.



Discussion

An object that inherits from NSObject must be prepared for use in two steps:

1. Allocation

2. Initialization

The allocation is done by invoking the alloc method, which is implemented in the

NSObject class. This method creates the internal structure of a new object and sets all

instance variables’ values to zero. After this step is done, the init method takes care of

setting up the default values of variables and performing other tasks, such as instantiating other internal objects.

Let’s look at an example. We are creating a class named MyObject. Here is the .h file:

#import

@interface MyObject : NSObject {

}

- (void) doSomething;

@end



6 | Chapter 1: Working with Objects



www.it-ebooks.info



The implementation of this class is as follows (the .m file):

#import "MyObject.h"

@implementation MyObject

- (void) doSomething{

/* Perform a task here */

NSLog(@"%s", __FUNCTION__);

}

@end



The doSomething instance method of the MyObject object will attempt to print the name

of the current function to the console window. Now let’s go ahead and invoke this

method by instantiating an object of type MyObject:

MyObject *someObject = [[MyObject alloc] init];

/* Do something with the object, call some methods, etc. */

[someObject doSomething];

[someObject release];



This code will work absolutely fine. Now try to skip initializing your object:

MyObject *someObject = [MyObject alloc];

/* Do something with the object, call some methods, etc. */

[someObject doSomething];

[someObject release];



If you run this code now, you will realize that it works absolutely fine, too. So, what

has happened here? We thought we had to initialize the object before we could use it.

Perhaps Apple can explain this behavior better:

An object isn’t ready to be used until it has been initialized. The init method defined in

the NSObject class does no initialization; it simply returns self.



Simply put, this means the init method is a placeholder for tasks that some classes

need to perform before they are used, such as setting up extra data structures or opening

files. NSObject itself—along with many of the classes you will use—does not have to

initialize anything in particular. However, it is a good programming practice to always

run the init method of an object after allocating it in case the parent of your class has

overridden this method to provide a custom initialization. Please bear in mind that the

return value for initializer methods of an object is of type id, so the initializer method

might even return an object that is not the same object that the alloc method returned

to you. This technique is called Two-Stage Creation and is extremely handy. However,

discussing this technique is outside the scope of this book. For more information about

Two-Stage Creation, please refer to Cocoa Design Patterns by Erik M. Buck and Donald

A. Yacktman (Addison-Wesley Professional).



1.2 Allocating and Initializing Objects | 7



www.it-ebooks.info



Xem Thêm
Tải bản đầy đủ (.pdf) (640 trang)

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×