`

Learning Objective-C: A Primer

    博客分类:
  • Mac
阅读更多

Referenced from: http://developer.apple.com/mac/library/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/index.html#//apple_ref/doc/uid/TP40007594

 

=====================================================

Mac OS X Reference Library Apple Developer Connection spyglass button
Search Mac Reference Library

Learning Objective-C: A Primer

Learning Objective-C: A Primer

The Objective-C language is a simple computer language designed to enable sophisticated object-oriented programming. Objective-C extends the standard ANSI C language by providing syntax for defining classes, and methods, as well as other constructs that promote dynamic extension of classes. (This document doesn’t attempt to teach any aspects of C itself. If you’re not familiar with the language, you should learn about the basics before you proceed.)

If you have programmed with object-oriented languages before, the following information should help you learn the basic syntax of Objective-C. Many of the traditional object-oriented concepts, such as encapsulation, inheritance, and polymorphism, are all present in Objective-C. There are a few important differences, but those differences are called out in this article and more detailed information is available if you need it.

If you have never programmed using an object-oriented language before, you need to have at least a basic understanding of the associated concepts before proceeding. The use of objects and object-oriented design patterns is fundamental to the design of Cocoa applications, and understanding how they interact is critical to creating your applications. For an overview of concepts, see Object-Oriented Programming with Objective-C . In addition, see Cocoa Fundamentals Guide for information about the design patterns used in Cocoa.

For full details of the Objective-C language and syntax, see The Objective-C Programming Language .

Objective-C: A Superset of C

Objective-C is a superset of the ANSI version of the C programming language and supports the same basic syntax as C. As with C code, you define header files and source files to separate public declarations from the implementation details of your code. Objective-C header files use the file extensions listed in Table 1 .

Table 1   File extensions for Objective-C code

Extension

Source type

.h

Header files. Header files contain class, type, function, and constant declarations.

.m

Source files. This is the typical extension used for source files and can contain both Objective-C and C code.

.mm

Source files. A source file with this extension can contain C++ code in addition to Objective-C and C code. This extension should be used only if you actually refer to C++ classes or features from your Objective-C code.

When you want to include header files in your source code, you typically use a #import directive. This is like #include , except that it makes sure that the same file is never included more than once. The Objective-C samples and documentation all prefer the use of #import , and your own code should too.

Classes

As in most other object-oriented languages, classes in Objective-C provide the basic construct for encapsulating some data with the actions that operate on that data. An object is a runtime instance of a class, and contains its own in-memory copy of the instance variables declared by that class and pointers to the methods of the class.

The specification of a class in Objective-C requires two distinct pieces: the interface and the implementation. The interface portion contains the class declaration and defines the instance variables and methods associated with the class. The interface is usually in a .h file. The implementation portion contains the actual code for the methods of the class. The implementation is usually in a .m file.

Figure 1 shows the syntax for declaring a class called MyClass , which inherits from the NSObject base class. The class declaration always begins with the @interface compiler directive and ends with the @end directive. Following the class name (and separated from it by a colon) is the name of the parent class. The instance (or member) variables of the class are declared in a code block that is delineated by braces ({ and } ). Following the instance variable block is the list of methods declared by the class. A semicolon character marks the end of each instance variable and method declaration.


Figure 1   A class declaration

A class declaration
Note:  Although this class declaration declares only methods, classes can also declare properties. For more information on properties, see “Declared Properties” .

When storing objects in variables, you always use a pointer type. Objective-C supports both strong and weak typing for variables containing objects. Strongly typed pointers include the class name in the variable type declaration. Weakly typed pointers use the type id for the object instead. Weakly typed pointers are used frequently for things such as collection classes, where the exact type of the objects in a collection may be unknown. If you are used to using strongly typed languages, you might think that the use of weakly typed variables would cause problems, but they actually provide tremendous flexibility and allow for much greater dynamism in Objective-C programs.

The following example shows strongly and weakly typed variable declarations:

MyClass *myObject1;  // Strong typing
id       myObject2;  // Weak typing

Notice the * in the first declaration. In Objective-C, object references are pointers. If this doesn’t make complete sense to you, don’t worry—you don’t have to be an expert with pointers to be able to start programming with Objective-C. You just have to remember to put the * in front of the variable names for strongly-typed object declarations.

Methods and Messaging

A class in Objective-C can declare two types of methods: instance methods and class methods. An instance method is a method whose execution is scoped to a particular instance of the class. In other words, before you call an instance method, you must first create an instance of the class. Class methods, by comparison, do not require you to create an instance, but more on that later.

The declaration of a method consists of the method type identifier, a return type, one or more signature keywords, and the parameter type and name information. Figure 2 shows the declaration of the insertObject:atIndex: instance method.


Figure 2   Method declaration syntax

Method declaration syntax

This declaration is preceded by a minus (- ) sign, which indicates that this is an instance method. The method’s actual name (insertObject:atIndex: ) is a concatenation of all of the signature keywords, including colon characters. The colon characters declare the presence of a parameter. If a method has no parameters, you omit the colon after the first (and only) signature keyword. In this example, the method takes two parameters.

When you want to call a method, you do so by messaging an object. A message is the method signature, along with the parameter information the method needs. All messages you send to an object are dispatched dynamically, thus facilitating the polymorphic behavior of Objective-C classes.

Messages are enclosed by brackets ([ and ] ). Inside the brackets, the object receiving the message is on the left side and the message (along with any parameters required by the message) is on the right. For example, to send the insertObject:atIndex: message to an object in the myArray variable, you would use the following syntax:

[myArray insertObject:anObject atIndex:0];

To avoid declaring numerous local variables to store temporary results, Objective-C lets you nest messages. The return value from each nested message is used as a parameter, or as the target, of another message. For example, you could replace any of the variables used in the previous example with messages to retrieve the values. Thus, if you had another object called myAppObject that had methods for accessing the array object and the object to insert into the array, you could write the preceding example to look something like the following:

[[myAppObject theArray] insertObject:[myAppObject objectToInsert] atIndex:0];

Objective-C also provides a dot syntax for invoking accessor methods . Accessor methods get and set the state of an object, and typically take the form -(type) propertyName and -(void)set PropertyName :(type) . Using dot syntax, you could rewrite the previous example as:

[myAppObject.theArray insertObject:[myAppObject objectToInsert] atIndex:0];

You can also use dot syntax for assignment:

myAppObject.theArray = aNewArray;

This is simply a different syntax for writing, [myObject setTheArray:aNewArray]; .

Although the preceding examples sent messages to an instance of a class, you can also send messages to the class itself. When messaging a class, the method you specify must be defined as a class method instead of an instance method. You can think of class methods as something akin to (but not exactly like) static members in a C++ class.

You typically use class methods as factory methods to create new instances of the class or for accessing some piece of shared information associated with the class. The syntax for a class method declaration is identical to that of an instance method, with one exception. Instead of using a minus sign for the method type identifier, you use a plus (+) sign.

The following example illustrates how you use a class method as a factory method for a class. In this case, the array method is a class method on the NSArray class—and inherited by NSMutableArray —that allocates and initializes a new instance of the class and returns it to your code.

NSMutableArray *myArray = nil;  // nil is essentially the same as NULL
 
// Create a new array and assign it to the myArray variable.
myArray = [NSMutableArray array];

Listing 1 shows the implementation of MyClass from the preceding example. Like the class declaration, the class implementation is identified by two compiler directives—here, @implementation and @end . These directives provide the scoping information the compiler needs to associate the enclosed methods with the corresponding class. A method’s definition therefore matches its corresponding declaration in the interface, except for the inclusion of a code block.

Listing 1   A class implementation

@implementation MyClass
 
- (id)initWithString:(NSString *)aName
{
    if (self = [super init]) {
        name = [aName copy];
    }
    return self;
}
 
+ (MyClass *)createMyClassWithString: (NSString *)aName
{
    return [[[self alloc] initWithString:aName] autorelease];
}
@end

Declared Properties

Declared properties are a convenience notation used to replace the declaration and, optionally, implementation of accessor methods.

You include property declarations with the method declarations in your class interface. The basic definition uses the @property compiler directive, followed by the type information and name of the property. You can also configure the property with custom options, which define how the accessor methods behave. The following example shows a few simple property declarations:

@property BOOL flag;
@property (copy) NSString *nameObject;  // Copy the object during assignment.
@property (readonly) UIView *rootView;  // Declare only a getter method.

Each readable property specifies a method with the same name as the property. Each writable property specifies an additional method of the form set PropertyName : , where the first letter of the property name is capitalized.

In your class implementation, you can use the @synthesize compiler directive to ask the compiler to generate the methods according to the specification in the declaration:

@synthesize flag;
@synthesize nameObject;
@synthesize rootView;

You can combine the @synthesize statements in a single line if you want:

@synthesize flag, nameObject, rootView;

Practically speaking, properties reduce the amount of redundant code you have to write. Because most accessor methods are implemented in similar ways, properties eliminate the need to implement a getter and setter method for each property exposed in the class. Instead, you specify the behavior you want using the property declaration and then synthesize actual getter and setter methods based on that declaration at compile time.

For information on how to declare properties in your own classes, read Declared Properties in The Objective-C Programming Language .

Strings

As a superset of C, Objective-C supports the same conventions for specifying strings as C. In other words, single characters are enclosed by single quotes and strings of characters are surrounded by double quotes. However, most Objective-C frameworks do not use C-style strings very often. Instead, most frameworks pass strings around in NSString objects.

The NSString class provides an object wrapper for strings that has all of the advantages you would expect, including built-in memory management for storing arbitrary-length strings, support for Unicode, printf -style formatting utilities, and more. Because such strings are used commonly though, Objective-C provides a shorthand notation for creating NSString objects from constant values. To use this shorthand, all you have to do is precede a normal, double-quoted string with the @ symbol, as shown in the following examples:

NSString *myString = @"My String\n";
NSString *anotherString = [NSString stringWithFormat:@"%d %s", 1, @"String"];
 
// Create an Objective-C string from a C string
NSString *fromCString = [NSString stringWithCString:"A C string" encoding:NSASCIIStringEncoding];

Protocols and Delegates

A protocol declares methods that can be implemented by any class. Protocols are not classes themselves. They simply define an interface that other objects are responsible for implementing. When you implement the methods of a protocol in one of your classes, your class is said to conform to that protocol.

Protocols are used frequently to specify the interface for delegate objects. A delegate object is an object that acts on behalf of, or in coordination with, another object. The best way to look at the interplay between protocols, delegates, and other objects is to look at an example.

The UIApplication class implements the required behavior of an application. Instead of forcing you to subclass UIApplication to receive simple notifications about the current state of the application, the UIApplication class delivers those notifications by calling specific methods of its assigned delegate object. An object that implements the methods of the UIApplicationDelegate protocol can receive those notifications and provide an appropriate response.

The declaration of a protocol looks similar to that of a class interface, with the exceptions that protocols do not have a parent class and they do not define instance variables. The following example shows a simple protocol declaration with one method:

@protocol MyProtocol
- (void)myProtocolMethod;
@end

In the case of many delegate protocols, adopting a protocol is simply a matter of implementing the methods defined by that protocol. There are some protocols that require you to state explicitly that you support the protocol, and protocols can specify both required and optional methods. As you get further into your development, however, you should spend a little more time learning about protocols and how they are used by reading Protocols in The Objective-C Programming Language .

For More Information

The preceding information was intended primarily to familiarize you with the basics of the Objective-C language. The subjects covered here reflect the language features you are most likely to encounter as you read through the rest of the documentation. These are not the only features of the language though, and you are encouraged to read more about the language in The Objective-C Programming Language .



Last updated: 2009-06-25

<!-- start of footer -->
Did this document help you? Yes It's good, but... Not helpful...

Shop the Apple Online Store (1-800-MY-APPLE), visit an Apple Retail Store , or find a reseller .

Copyright © 2009 Apple Inc. All rights reserved.

<!-- /globalfooter-->
<!-- end of footer -->

<!-- start of path -->

<!-- end of path -->

<object id="QuickLookArticle" type="text/html"> </object>

分享到:
评论

相关推荐

    高清彩版 Programming in Objective-C(6th)

    Objective-C是苹果公司用于iOS和OS X应用开发的编程语言,由于其与C语言的兼容性以及面向对象的特性,使其成为苹果早期开发者的首选语言。 书中提到了“Developer’s Library”,这是一套专门为编程专业人士设计的...

    Programming in Objective-C (4th Edition)

    通过上述分析,可以看出《Programming in Objective-C (4th Edition)》是一本为程序员准备的实用教程,它不仅覆盖了Objective-C语言的基础知识,还结合了Xcode开发工具和iOS 5平台的开发环境,适合初学者和希望提升...

    C-Primer-Plus:C Primer Plus 5个答案

    C-Primer-PlusC Primer Plus 5 answers (by PytLab)C Primer Plus(第五版) 编程练习答案(全部本人所写,仅供参考)###Table of Content

    Programming in Objective-C

    总之,《Programming in Objective-C》不仅为初学者提供了一个学习Objective-C语言的平台,也为想要深入了解iOS开发的开发者们提供了一条清晰的学习路径。通过这本书,开发者们能够逐步掌握Objective-C编程基础以及...

    Programming in Objective-C, 6th Edition

    综上所述,这本《Programming in Objective-C, 6th Edition》是一本针对苹果操作系统的应用开发者的权威教材,旨在提供Objective-C语言的系统性学习和应用指导。它着重强调了Objective-C编程技能的学习,为开发者...

    Primer-BLAST:NCBI的引物设计和特异性检验工具

    ### Primer-BLAST:NCBI的引物设计与特异性检验工具 #### 一、Primer-BLAST概述 Primer-BLAST是一款由美国国立卫生研究院下属的国家生物技术信息中心(NCBI)开发的在线工具,专门用于设计特异性寡核苷酸引物,...

    c#毕业设计源码-Cpp-Primer:C++Primer5答案

    Primer 5答案(C ++ 11/14) 编译器推荐 Windows:Visual Studio 2015+ Linux:g ++ 5.0以上 g++ -std=c++14 some_ex.cpp -o some_ex Mac:clang ++ 3.7+ clang++ -std=c++1y some_ex.cpp -o some_ex 内容 第一部分...

    Pr-ctica-5--SGE:Primer acercamiento a python trabajando con ficheros

    标题 "Pr-ctica-5--SGE:Primer acercamiento a python trabajando con ficheros" 暗示这是一个关于使用Python处理文件的基础教程。在这个实践中,我们将深入探讨Python编程语言如何有效地操作文件和目录,这是任何...

    primer3-py:简单的寡核苷酸分析和引物设计

    primer3-py:简单的寡核苷酸分析和引物设计 Primer3-py是流行的Primer3库的Python抽象API。 目的是为自动化寡核苷酸分析和设计提供一个简单可靠的界面。 常规寡核苷酸分析很简单: &gt;&gt;&gt; import primer3&gt;&gt;&gt; primer3....

    java坑爹的笔试题-cpp-primer-5th:C++Primer第五版学习资料

    ,第8、9章最为重要,IO库和容器对于一个程序来说是比较基础的,记得不要在C++中还依然保持C的习惯,使用cout而不是printf()、使用vector而不是内置数组、使用迭代器进行遍历。第10、11章有点基础的看起来不是很难,...

    ember-primer:Ember Primer是用于构建雄心勃勃的数据可视化的原语的集合

    @primer Ember Primer是数据可视化原语(组件)的集合,可以将它们组合在一起以构建雄心勃勃的数据可视化和交互式演示。 Ember Primer由构建和维护, 是易于使用的负载测试平台,可用于任何规模的测试。 底漆有3个...

    C-Primer-Exercise:C++ Primer 5 Edition 课后习题解,边阅读边补充,有解答不正确的地方,欢迎提issue

    课后习题是检验学习成果和加深理解的重要环节,而"C-Primer-Exercise"则提供了对这些习题的解答,旨在帮助读者巩固所学知识。 在阅读《C++ Primer 5th Edition》时,与书中的练习题进行互动是非常有益的。这些习题...

    c++primerplus 课后习题答案

    C++primerplus 课后习题答案 C++primer plus 是一本非常好的 C++ 教程书籍,旨在帮助初学者和中级程序员快速学习 C++ 编程语言。该书籍提供了详细的讲解、实例代码和练习题,以帮助读者更好地理解 C++ 编程语言的...

    primervector-matlab:使用Primer Vector理论Pontryagin最大原理的Matlab火箭弹道优化

    《基于Primer Vector理论与Pontryagin最大原理的Matlab火箭弹道优化》 在现代航天工程中,火箭弹道优化是一项至关重要的任务,它涉及到火箭的性能提升、飞行安全以及有效载荷的投放等多个关键因素。本文将深入探讨...

Global site tag (gtag.js) - Google Analytics