89394556 2009-12-18
Referenced from: http://developer.apple.com/mac/library/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/index.html#//apple_ref/doc/uid/TP40007594
=====================================================
Learning Objective-C: A PrimerTheObjective-C language is a simple computer language designed to enablesophisticated object-oriented programming. Objective-C extends thestandard ANSI C language by providing syntax for defining classes, andmethods, as well as other constructs that promote dynamic extension ofclasses. (This document doesn’t attempt to teach any aspects of Citself. If you’re not familiar with the language, you should learnabout the basics before you proceed.) If you have programmed withobject-oriented languages before, the following information should helpyou learn the basic syntax of Objective-C. Many of the traditionalobject-oriented concepts, such as encapsulation, inheritance, andpolymorphism, are all present in Objective-C. There are a few importantdifferences, but those differences are called out in this article andmore detailed information is available if you need it. If youhave never programmed using an object-oriented language before, youneed to have at least a basic understanding of the associated conceptsbefore proceeding. The use of objects and object-oriented designpatterns is fundamental to the design of Cocoa applications, andunderstanding how they interact is critical to creating yourapplications. 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 CObjective-Cis a superset of the ANSI version of the C programming language andsupports the same basic syntax as C. As with C code, you define headerfiles and source files to separate public declarations from theimplementation details of your code. Objective-C header files use thefile 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
Sourcefiles. A source file with this extension can contain C++ code inaddition to Objective-C and C code. This extension should be used onlyif you actually refer to C++ classes or features from your Objective-Ccode.
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 morethan once. The Objective-C samples and documentation all prefer the useof #import
, and your own code should too.
Asin most other object-oriented languages, classes in Objective-C providethe basic construct for encapsulating some data with the actions thatoperate on that data. An object is a runtime instance of a class, andcontains its own in-memory copy of the instance variables declared bythat class and pointers to the methods of the class.
Thespecification of a class in Objective-C requires two distinct pieces:the interface and the implementation. The interface portion containsthe class declaration and defines the instance variables and methodsassociated 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 ofthe class are declared in a code block that is delineated by braces ({
and }
).Following the instance variable block is the list of methods declaredby the class. A semicolon character marks the end of each instancevariable and method declaration.
Figure 1 A class declaration
Whenstoring objects in variables, you always use a pointer type.Objective-C supports both strong and weak typing for variablescontaining objects. Strongly typed pointers include the class name inthe variable type declaration. Weakly typed pointers use the type id
for the object instead. Weakly typed pointers are used frequently forthings such as collection classes, where the exact type of the objectsin a collection may be unknown. If you are used to using strongly typedlanguages, you might think that the use of weakly typed variables wouldcause problems, but they actually provide tremendous flexibility andallow 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 arepointers. If this doesn’t make complete sense to you, don’t worry—youdon’t have to be an expert with pointers to be able to startprogramming with Objective-C. You just have to remember to put the *
in front of the variable names for strongly-typed object declarations.
Aclass in Objective-C can declare two types of methods: instance methodsand class methods. An instance method is a method whose execution isscoped to a particular instance of the class. In other words, beforeyou call an instance method, you must first create an instance of theclass. Class methods, by comparison, do not require you to create aninstance, but more on that later.
The declaration of a methodconsists of the method type identifier, a return type, one or moresignature keywords, and the parameter type and name information. Figure 2 shows the declaration of the insertObject:atIndex:
instance method.
Figure 2 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 coloncharacters. The colon characters declare the presence of a parameter.If a method has no parameters, you omit the colon after the first (andonly) signature keyword. In this example, the method takes twoparameters.
When you want to call a method, you do so by messagingan object. A message is the method signature, along with the parameterinformation the method needs. All messages you send to an object aredispatched dynamically, thus facilitating the polymorphic behavior ofObjective-C classes.
Messages are enclosed by brackets ([
and ]
).Inside the brackets, the object receiving the message is on the leftside and the message (along with any parameters required by themessage) 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]; |
Toavoid declaring numerous local variables to store temporary results,Objective-C lets you nest messages. The return value from each nestedmessage is used as a parameter, or as the target, of another message.For example, you could replace any of the variables used in theprevious example with messages to retrieve the values. Thus, if you hadanother object called myAppObject
that had methods foraccessing the array object and the object to insert into the array, youcould 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];
.
Althoughthe preceding examples sent messages to an instance of a class, you canalso send messages to the class itself. When messaging a class, themethod you specify must be defined as a class method instead of aninstance method. You can think of class methods as something akin to(but not exactly like) static members in a C++ class.
Youtypically use class methods as factory methods to create new instancesof the class or for accessing some piece of shared informationassociated with the class. The syntax for a class method declaration isidentical to that of an instance method, with one exception. Instead ofusing 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 classimplementation is identified by two compiler directives—here, @implementation
and @end
.These directives provide the scoping information the compiler needs toassociate the enclosed methods with the corresponding class. A method’sdefinition therefore matches its corresponding declaration in theinterface, 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 |
Declaredproperties are a convenience notation used to replace the declarationand, 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 theproperty. You can also configure the property with custom options,which define how the accessor methods behave. The following exampleshows 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. |
Eachreadable property specifies a method with the same name as theproperty. Each writable property specifies an additional method of theform 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; |
Practicallyspeaking, properties reduce the amount of redundant code you have towrite. Because most accessor methods are implemented in similar ways,properties eliminate the need to implement a getter and setter methodfor each property exposed in the class. Instead, you specify thebehavior you want using the property declaration and then synthesizeactual getter and setter methods based on that declaration at compiletime.
For information on how to declare properties in your own classes, read Declared Properties in The Objective-C Programming Language.
Asa superset of C, Objective-C supports the same conventions forspecifying strings as C. In other words, single characters are enclosedby single quotes and strings of characters are surrounded by doublequotes. However, most Objective-C frameworks do not use C-style stringsvery often. Instead, most frameworks pass strings around in NSString
objects.
The NSString
class provides an object wrapper for strings that has all of theadvantages you would expect, including built-in memory management forstoring arbitrary-length strings, support for Unicode, printf
-styleformatting utilities, and more. Because such strings are used commonlythough, 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]; |
Aprotocol declares methods that can be implemented by any class.Protocols are not classes themselves. They simply define an interfacethat other objects are responsible for implementing. When you implementthe methods of a protocol in one of your classes, your class is said toconform to that protocol.
Protocols are used frequently tospecify the interface for delegate objects. A delegate object is anobject that acts on behalf of, or in coordination with, another object.The best way to look at the interplay between protocols, delegates, andother 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 itsassigned delegate object. An object that implements the methods of the UIApplicationDelegate
protocol can receive those notifications and provide an appropriate response.
Thedeclaration of a protocol looks similar to that of a class interface,with the exceptions that protocols do not have a parent class and theydo not define instance variables. The following example shows a simpleprotocol declaration with one method:
@protocol MyProtocol |
- (void)myProtocolMethod; |
@end |
Inthe case of many delegate protocols, adopting a protocol is simply amatter of implementing the methods defined by that protocol. There aresome protocols that require you to state explicitly that you supportthe protocol, and protocols can specify both required and optionalmethods. As you get further into your development, however, you shouldspend a little more time learning about protocols and how they are usedby reading Protocols in The Objective-C Programming Language.
Thepreceding information was intended primarily to familiarize you withthe basics of the Objective-C language. The subjects covered herereflect the language features you are most likely to encounter as youread through the rest of the documentation. These are not the onlyfeatures of the language though, and you are encouraged to read moreabout the language in The Objective-C Programming Language.
Last updated: 2009-06-25
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.
<!-- start of path -->
<!-- end of path -->