ios developer tiny share-20160815

来源:互联网 发布:淘宝上如何修改评价 编辑:程序博客网 时间:2024/06/14 18:28

今天讲Objective-C的“Objects Send and Receive Messages”,实际就是调用类的方法的语法。

在开头,我们还是Overview下“Working with Objects”话题:

Working with Objects

The majority of work in an Objective-C application happens as a result of messages being sent back and forth across an ecosystem of objects. Some of these objects are instances of classes provided by Cocoa or Cocoa Touch, some are instances of your own classes.

The previous chapter described the syntax to define the interface and implementation for a class, including the syntax to implement methods containing the code to be executed in response to a message. This chapter explains how to send such a message to an object, and includes coverage of some of Objective-C’s dynamic features, including dynamic typing and the ability to determine which method should be invoked at runtime.

Before an object can be used, it must be created properly using a combination of memory allocation for its properties and any necessary initialization of its internal values. This chapter describes how to nest the method calls to allocate and initialize an object in order to ensure that it is configured correctly.


Objects Send and Receive Messages

Although there are several different ways to send messages between objects in Objective-C, by far the most common is the basic syntax that uses square brackets, like this:

[someObject doSomething];

The reference on the left, someObject in this case, is the receiver of the message. The message on the right, doSomething, is the name of the method to call on that receiver. In other words, when the above line of code is executed, someObject will be sent the doSomething message.

The previous chapter described how to create the interface for a class, like this:

@interface XYZPerson : NSObject- (void)sayHello;@end

and how to create the implementation of that class, like this:

@implementation XYZPerson- (void)sayHello {    NSLog(@"Hello, world!");}@end

Note: This example uses an Objective-C string literal, @"Hello, world!". Strings are one of several class types in Objective-C that allow a shorthand literal syntax for their creation. Specifying @"Hello, world!" is conceptually equivalent to saying “An Objective-C string object that represents the string Hello, world!.”
Literals and object creation are explained further in Objects Are Created Dynamically, later in this chapter.


Assuming you’ve got hold of an XYZPerson object, you could send it the sayHello message like this:

[somePerson sayHello];

Sending an Objective-C message is conceptually very much like calling a C function. Figure 2-1 shows the effective program flow for the sayHello message.

Figure 2-1  Basic messaging program flow


In order to specify the receiver of a message, it’s important to understand how pointers are used to refer to objects in Objective-C.

0 0
原创粉丝点击