Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Objective-C.Programming.pdf
Скачиваний:
14
Добавлен:
21.02.2016
Размер:
8.64 Mб
Скачать

12

Objects

Many computer languages have the idea of objects. An object is like a structure in that it holds data. However, unlike a structure, an object also contains a set of functions that act upon that data. To trigger one of these functions, you send a message to the object. To use the correct word, a function that is triggered by a message is known as a method.

In the early 1980’s, Brad Cox and Tom Love decided to add object-oriented ideas to the C language. For objects, they built upon the idea of structs allocated on the heap and added a message-sending syntax. The result was the language Objective-C.

Objects are very chatty by nature. They do work and send and receive messages about the work they are doing. A complex Objective-C program can have hundreds of objects in memory all at once, doing work and sending messages to each other.

A class describes a particular type of object. This description includes methods and instance variables where an object of this type stores its data. You ask a class to create an object of its type for you on the heap. We say that the resulting object is an instance of that class.

For example, an iPhone ships with many classes, one of which is CLLocation. You can ask the CLLocation class to create an instance of CLLocation. Inside this CLLocation object are several instance variables that hold location data, like longitude, latitude, and altitude. The object also has several methods. For example, you can ask one instance of CLLocation how far it is from another

CLLocation object.

Creating and using your first object

Now you’re going to create your first Objective-C program. Create a new project: a Command Line Tool, but instead of C, make its type Foundation. Name it TimeAfterTime.

75

Chapter 12 Objects

Figure 12.1 Creating a Foundation command-line tool

Files containing Objective-C code are typically given the suffix .m. Find and open main.m and type in these two lines of code:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])

{

@autoreleasepool {

NSDate *now = [NSDate date];

NSLog(@"The new date lives at %p", now);

}

return 0;

}

Voilà! Your first message send. You sent the message date to the NSDate class. The date method asks the NSDate class to create an instance of NSDate, initialize it to the current date/time, and return the address where the new object starts. You then stored the returned address in the variable now. This variable is a pointer to an NSDate object.

NSLog() is an Objective-C function not unlike printf(); it takes a format string, replaces % tokens with actual values, and writes the result to the console. However, its format string always begins with an @, and it does not require a \n at the end.

Build and run the program. You should see something like:

2011-08-05 11:53:54.366 TimeAfterTime[4862:707] The new date lives at 0x100114dc0

Unlike printf(), NSLog() prefaces its output with the date, time, program name, and process ID. From now on when I show output from NSLog(), I’ll skip this data – the page is just too narrow.

In NSLog(), %p printed out the location of the object. To print out something more date-like, you can use %@, which asks the object to describe itself as a string:

76

Message anatomy

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])

{

@autoreleasepool {

NSDate *now = [NSDate date];

NSLog(@"The date is %@", now);

}

return 0;

}

Now you should see something like:

The date is 2011-08-05 16:09:14 +0000

Message anatomy

A message send is always surrounded by square brackets, and it always has at least two parts:

a pointer to the object that is receiving the message

the name of the method to be triggered

A message send (like a function call) can also have arguments. Let’s look at an example.

NSDate objects represent a particular date and time. An instance of NSDate can tell you the difference (in seconds) between the date/time it represents and 12:00AM (GMT) on Jan 1, 1970. Ask yours this question by sending the message timeIntervalSince1970 to the NSDate object pointed to by now.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])

{

@autoreleasepool {

NSDate *now = [NSDate date]; NSLog(@"The date is %@", now);

double seconds = [now timeIntervalSince1970];

NSLog(@"It has been %f seconds since the start of 1970.", seconds);

}

return 0;

}

Now say you want a new date object – one that is 100,000 seconds later from the one you already have.

The NSDate class has a method called dateByAddingTimeInterval:. You can send this message to the original date object to get the new date object. This method takes an argument: the number of seconds to add. Use it to create a new date object in your main() function:

77

Chapter 12 Objects

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])

{

@autoreleasepool {

NSDate *now = [NSDate date];

NSLog(@"The date is %@", now);

double seconds = [now timeIntervalSince1970];

NSLog(@"It has been %f seconds since the start of 1970.", seconds);

NSDate *later = [now dateByAddingTimeInterval:100000];

NSLog(@"In 100,000 seconds it will be %@", later);

}

return 0;

}

In the message send [now dateByAddingTimeInterval:100000],

now is a pointer to the object that is receiving the message (also known as “the receiver”)

dateByAddingTimeInterval: is the method name (also known as “the selector”)

100000 is the only argument

Figure 12.2 A message send

78

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]