BUY THIS BOOK
Add to Cart

Print Book $9.95


Add to Cart

Print+PDF $12.93

Add to Cart

PDF $7.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £6.95

What is this?

Looking to Reprint or License this content?


Objective-C Pocket Reference
Objective-C Pocket Reference By Andrew M. Duncan
December 2002
Pages: 128

Cover | Table of Contents


Table of Contents

Chapter 1: Objective-C Pocket Reference
The Objective-C Pocket Reference is a quick guide to the Objective-C programming language and some of its fundamental support libraries. This reference takes the form of brief explanations interspersed with examples and definitions. If you are experienced with Objective-C, this handbook will supply the definitions and examples you most often need to jog your memory. If you are coming to Objective-C from C++ or Java and prefer to jump right in and write code, this book will give you enough explanation to use the language's features appropriately.
You should be familiar with C-style languages in order to read this book. Objective-C uses C syntax. This book focuses only on Objective-C, and assumes that you understand the underlying C code.
This handbook progresses in sequence as much as possible, with later sections building on earlier ones, but some parts are necessarily interrelated. For example, the section on objects needs to refer to classes and vice versa. Both use the terminology of inheritance. Where you see an unfamiliar term used, check the index: it is probably defined elsewhere in the book.
Although Objective-C is (apart from its C base) a small language, the implications of its modest set of extensions are substantial. To use Objective-C effectively, you should follow tested design patterns and make judicious use of libraries. The intent of this handbook is to provide a quick reference to the most commonly used features and idioms of the language. It should be like a fast cache, the first stop for frequently used data.
Because of its size, this handbook can present only an outline of the language, its libraries, and conventional patterns of usage. If you are interested in truly understanding the Objective-C way of thinking, you should also look at some of the texts listed in Section 1.17 at the end of this book.
For supplementary information and corrections to this handbook, see our web site at
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
The Objective-C Pocket Reference is a quick guide to the Objective-C programming language and some of its fundamental support libraries. This reference takes the form of brief explanations interspersed with examples and definitions. If you are experienced with Objective-C, this handbook will supply the definitions and examples you most often need to jog your memory. If you are coming to Objective-C from C++ or Java and prefer to jump right in and write code, this book will give you enough explanation to use the language's features appropriately.
You should be familiar with C-style languages in order to read this book. Objective-C uses C syntax. This book focuses only on Objective-C, and assumes that you understand the underlying C code.
This handbook progresses in sequence as much as possible, with later sections building on earlier ones, but some parts are necessarily interrelated. For example, the section on objects needs to refer to classes and vice versa. Both use the terminology of inheritance. Where you see an unfamiliar term used, check the index: it is probably defined elsewhere in the book.
Although Objective-C is (apart from its C base) a small language, the implications of its modest set of extensions are substantial. To use Objective-C effectively, you should follow tested design patterns and make judicious use of libraries. The intent of this handbook is to provide a quick reference to the most commonly used features and idioms of the language. It should be like a fast cache, the first stop for frequently used data.
Because of its size, this handbook can present only an outline of the language, its libraries, and conventional patterns of usage. If you are interested in truly understanding the Objective-C way of thinking, you should also look at some of the texts listed in Section 1.17 at the end of this book.
For supplementary information and corrections to this handbook, see our web site at
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is Objective-C?
Objective-C is an object-oriented language: it supports hierarchies of substitutable types, message-passing between objects, and code reuse through inheritance. Objective-C adds these features to the familiar C programming language.
Because Objective-C is an extension of C, many properties of an Objective-C program depend on the underlying C development tools. Among these properties are:
  • The size of scalar variables such as integers and floating-point numbers
  • Allowed placement of scoped declarations
  • Implicit type conversion and promotion
  • Storage of string literals
  • Preprocessor macro expansion
  • Compiler warning levels
  • Code optimization
  • Include and link search paths
For more information about these topics, consult the documentation for your development platform and tools.
Objective-C differs from C++, another object-oriented extension of C, by deferring decisions until runtime that C++ would make at compile time. Objective-C is distinguished by the following key features:
  • Dynamic dispatch
  • Dynamic typing
  • Dynamic loading
Object-oriented languages replace function calls with messages . The difference is that the same message may trigger different code at runtime, depending on the type of the message receiver. Objective-C decides dynamically—at runtime—what code will handle a message by searching the receiver's class and parent classes. (The Objective-C runtime caches the search results for better performance.) By contrast, a C++ compiler constructs a dispatch table statically—at compile time.
Because the simple linear search for a receiver used by Objective-C mirrors the way we think about inheritance, it's easy to understand how an Objective-C program works. Dynamic dispatch can handle changes in the inheritance hierarchy at runtime. A dynamic message-sending model is also more natural for distributed objects than a table-based model.
Because message-sending is dynamic, Objective-C lets you send messages to objects whose type has not been declared. The Objective-C environment determines dynamically—at runtime—the class of the message receiver and calls the appropriate code. By comparison, C++ requires the type of the receiver to be declared statically—at compile time—in order to consult dispatch tables.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Elements of the Language
Objective-C extends the C language with the following concepts and constructs:
  • Objects (instances of classes)
  • Classes
  • Inheritance and subtyping
  • Fields
  • Methods and method calls (or messages)
  • Categories
  • Protocols
  • Declarations (extended from C to include class and protocol types)
  • Predefined types, constants, and variables
  • Compiler and preprocessor directives
The following sections will describe these aspects of Objective-C.
Objects are the compound values—data and operations—at the heart of object-oriented programming. They are generalizations of simple structured types found in C and many other languages. Like C structs, objects have components—data fields—that maintain state. For example, a Book object might have fields to specify the author and publisher. In addition, objects interact through message passing, which provides an alternative to the function calls of a procedural language.
Objective-C objects have these attributes:
Class
An object type. An object whose type is MyClass is said to be an instance of MyClass.
Fields
Data members of an object. An object has its own copies of the fields declared by its class or its ancestor classes.
Fields are also referred to as "instance variables." I prefer the term "fields" for several reasons: "instance variables" is redundant since there are no class variables, it is ambiguous since it could mean variables that are instances, just "variables" would be more ambiguous, and "fields" is shorter. (An alternative term is "ivars.")
Methods
Functions provided by an object. An object responds to methods declared by its class or ancestor classes.
A few special objects (class objects) acquire their fields and methods differently. Section 1.9 describes class objects.
Objective-C objects are implemented so that:
  • They exist in dynamically allocated memory.
  • They can't be declared on the stack or passed by value to other scopes.
  • They are referred to only by pointers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Compiler and Preprocessor Directives
Compiler and preprocessor directives are special terms in your program that tell the compiler to perform some Objective-C-specific action. All compiler directives start with the character @, and preprocessor directives start with #.
The following compiler directives are used to begin or conclude the declaration and definition of Objective-C classes, categories, and protocols:
@interface
Begins the declaration of a class's or category's fields and methods.
@protocol
Begins the declaration of a protocol's methods.
@implementation
Begins the definition of a class's methods.
@end
Ends the declaration or definition of a class's, category's, or protocol's methods.
The use of these compiler directives is described in detail under Section 1.3, and especially in the subsections Section 1.3.2, Section 1.3.6, and Section 1.3.7.
The following compiler directives generate forward declarations, informing the compiler that a type exists:
@class ClassName
Forward declaration of a class.
@protocol ProtocolName
Forward declaration of a protocol.
Use forward declarations when an interface uses variables (fields or method parameters or return types) of a given type. Rather than import the header file for that type, you can simply forward reference it. For example:
@class 
               Point;
@interface 
               Circle : Graphic {
  Point* center;
  // etc.
}
@end
This is sufficient because the declaration of Circle does not use any details of Point. You could import the header for Point, but this makes any other class that imports Circle.h appear dependent also on Point.h, and can cause unnecessary (and slow) recompiling in large projects.
Expanding complier directives look like functions, but they are really instructions to the compiler, which expands them as described in the following list:
@encode ( typeName )
Takes a type specification and evaluates to the C string used by the runtime to succinctly describe that type.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Compiler Flags
Compiler flags are options you give to gcc when it compiles a file or set of files. You may provide these directly on the command line, or your development tools may generate them when they invoke gcc. This section describes just the flags that are specific to Objective-C.
-fconstant-string-class= ClassName
Tells the compiler to create an instance of ClassName for each string literal expressed with the @"string" directive. For the GNU runtime, the default class is NXConstantString; for Cocoa it is NSConstantString.
-fgnu-runtime
Generate code for linking with the standard GNU Objective-C runtime. This is the default option for most gcc installations.
-fnext-runtime
Generate code for linking with the NeXT runtime. This is the default option for Darwin.
-gen-decls
Write all interface declarations the compiler sees to a file named sourcename.decl.
-Wno-protocol
Do not warn if methods required by a protocol are not implemented in the class adopting it.
-Wselector
Warn if there are methods with the same name but different signatures.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Remote Messaging
Objective-C's method call model lends itself well to distributed systems, where sending messages is the fundamental unit of interaction. The key difference in distributed systems is that objects may exist in different address spaces, and so cannot call each other directly.
Objects that want to receive messages from other processes must specify those messages in a formal protocol. Objective-C provides special keywords to use when writing such a formal protocol that qualify the kind of sharing you will need for that protocol's message parameters.
You use the keywords to modify (or qualify) the type of a method's parameter or return value. For example, the keywords out and in modify the parameters in the following declaration:
-(void)getData:(out 
            Data*)data 
            forIndex:(in 
            int)index;
The signature of this method says that index is only passed in and changes to it don't need to be returned, but the method will modify the value of data.
You can't use these keywords in class or category declarations. However, if your class or category adopts a protocol that uses a remote messaging keyword, you can repeat the keyword in the method signature of the implementation.
The remote messaging keywords can be grouped into three categories: those for pointer parameters, those for return values, and those for object qualifiers.
This section discusses qualifiers that generally apply to pointer arguments. They tell the compiler how to handle copying values between address spaces so that the pointers can be dereferenced in both spaces and see the same value. The pointer parameter qualifiers are as follows:
in
You will reading directly from the parameter, or will dereference the parameter to read a value but not to write one. This qualifier can be used for non-pointers.
out
You will dereference the parameter to write a value but not to read one. This qualifier applies only to pointers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Object Lifecycle
Your classes will have methods that distinguish them from other classes and make them useful, but all classes must implement methods that manage their lifecycle—allocation, initialization, copying, and deletion. In addition, you will use library classes that come supplied with these methods, which you need to use in a consistent way. This section describes the design patterns that Objective-C programmers use and that library classes support.
The root classes Object and NSObject provide the following methods for managing the lifecycles of objects:
+initialize
+alloc
+new
-init
-copy
-dealloc
In addition, Object also provides these methods:
-shallowCopy
-deepCopy
-deepen
-free
In addition to these methods, many classes will provide more methods for initializing newly allocated objects.
Section 1.10 describes how these methods behave for the root classes; this section gives you guidelines on how to actually use the methods in your programs.
In managing the lifecycle of an object, you are faced with two issues: how to call these methods and how to write them for your own classes. Each of the following sections will first discuss how to call the methods, and then how to write them.
Objective-C separates object creation into two steps: allocating memory and initializing fields. Allocation returns a pointer to cleared memory where the object will be stored. Initializing an object means setting its fields to some values, either default or specified. These operations serve distinct purposes, are performed by different objects (allocation by a class, and initialization by an instance), and you write and call each of them explicitly.

Section 1.7.1.1: Calling creation methods

To create an object, you first ask its class to allocate memory, and then you initialize the instance:
1Circle* c = [Circle alloc];
2 c = [c init];
Line 1. In Objective-C you call a class method to return a pointer to memory for a new object. It is conventional to call this method
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Runtime Errors
Runtime errors include program errors like unhandled method calls or messages sent to released objects, and hardware errors like division by zero. The Object root class provides simple error-handling capability; the Cocoa framework implements exception raising and handling.
When an error occurs, the runtime sets in motion the following sequence of events:
  1. The runtime calls the -error : method on the object whose method generated the error. You can override this method to customize error handling for a particular class.
  2. The -error: method prepares information about the receiver and passes it to the runtime C function objc_verror( ) .
  3. The objc_verror( ) function calls the runtime error handler function if there is one; otherwise it writes an error message to stderr. You can provide a handler function to customize error handling for all classes.
  4. If the error handler exists (because you've provided one) and it returns YES, execution continues; otherwise the program calls the C function abort( ) and exits.
The GNU runtime provides a function to set your own error handler function:
objc_error_handler objc_set_error_handler(objc_error_handlerf)
Calling this function sets a new error handler and returns the previous one. The default error handler is a NULL pointer. The required signature of an error handler is declared (in objc-api.h) as:
typedef 
               BOOL (*objc_error_handler)
  (id receiver, 
   int errCode, 
   const 
               char* format, 
   va_list args);
Here are descriptions of the parameters your error handler will get:
receiver
The object in whose method the error occurred.
errCode
One of a set of integers declared in the header file objc-api.h along with objc_error_handler .
format
A printf-style C string, for printing an error message.
args
A variable-length list of values for the format string. You can print the error message using the format and argument list and the C function
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Runtime Environment
When your Objective-C program is running, certain structures and services are always set up for you, even though you don't specifically ask for them. These serve as the counterpart to the compiler: together the compiler and the runtime implement the features that Objective-C adds to C. Most languages include runtime environments; Objective-C is distinctive in exposing a good part of its runtime in a public programming interface.
The runtime's interfaces are in header files that will be present in any installation of gcc. (For example, in Darwin they reside at /usr/include/objc. Check your compiler's default include paths to locate these files.) You can also download the source code for the runtime; examining it is a good way to learn more about how dynamic languages are implemented.
Class objects are objects that represent at runtime the classes a program is using. Because they function in the same way as regular objects—you can send them messages and use them in expressions—Objective-C unifies the treatment of classes and their instances.
Class objects are also called factory objects, because in their most common usage you send them the +alloc message to create other objects.
Class objects are set up by the Objective-C compiler and initialized at runtime before your code needs to use them. To get a class object from an instance, use the -class method. For example, given an instance created this way:
Circle* c = [Circle new];
you can retrieve the class object of that instance like this:
ClasscircleClass = [c class];
Sending a message to a class object is common enough that it has a shortcut: just name the class as the receiver, as you do when you invoke +alloc.
In the Objective-C runtime all regular objects start with an isa field, pointing to their class object. The class object contains (or refers to) the instance methods that the object can respond to. In addition each class object has a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Root Classes
A root class is one with no parent class. Objective-C allows multiple root classes, but you are most likely to use one supplied with your compiler.
All Objective-C distributions provide a root class called Object. This section describes the Object supplied with the GNU runtime. The Object class provided by Darwin is similar, but Darwin users will be more likely to use the NSObject root class that comes with the Cocoa class library. (The GNUstep library also provides an NSObject root class almost identical to Cocoa's.) This section describes the fields and methods of both Object and NSObject.
Both classes provide access to Objective-C features like reflection, memory management, and archiving. Most of the classes you write will inherit from one of these classes, so your objects will be able to use these features.
The runtime goes to some length to make class objects behave the same as regular objects. In particular, they appear to inherit their fields and methods from the root classes, so they share in the properties described in this section.
Both Object and NSObject declare only one field, isa , whose type is Class. This field is inherited by all their descendants, which is critical to the operation of inheritance and message dispatch. It points to the class object representing the instance's class. See Section 1.9 earlier in this book.
Root class methods are accessible from any object that derives from the class—usually all regular objects in a program. In addition, root class instance methods can be called on class objects for it and its subclasses—in other words, class objects appear to be instances of their root class. (The runtime arranges for this; see Section 1.9.2 under Section 1.9.)
Because you can call root class instance methods on class objects, the behavior of some instance methods described here has several distinct, though consistent, cases:
  • The receiver is a regular object.
  • The receiver is a class object.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Forwarding Messages
When an object is sent a message for which it has no method, the runtime system gives it another chance to handle the call before giving up. If the object supports a -forward :: method, the runtime calls this method, passing it information about the unhandled call. The return value from the forwarded call is propagated back to the original caller of the method.
Both Object and NSObject provide a -forward:: method, so all objects you are likely to encounter will behave as described in this section. In each case, the default behavior, implemented by the root class method, is to exit the program when an unhandled call is forwarded. Your classes can override this method to provide alternative behavior; common choices are to absorb the error or to redirect (forward) the unhandled message to another object, which is called a delegate .
The -forward:: method takes a selector and a second parameter that stores information about the parameters passed to the original (failed) method call.
The method supplied by GNU's Object sets off the following train of events:
  1. -forward:: calls -doesNotRecognize : on self, passing the selector for the original method call.
  2. -doesNotRecognize: in turn calls -error : passing a format string and the name of the original method call.
  3. -error: logs an error message and aborts the program, unless you have overridden this method or installed an alternative error handler. Section 1.8 discusses this more.
If you want to just ignore messages that your class does not handle, you can override -forward:: to return NULL. To implement true forwarding for a class, override the -forward:: method in the following way:
1 -(retval_t)forward:(SEL)sel :(arglist_t)args {
2   if ([myDelegate respondsTo:sel])
3     return [myDelegate performv:sel :args]
4   else
5     return [super forward:sel :args];
6 }
Line 2. Check that the delegate actually handles the call. The
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Memory Management
The liveness of an object—whether or not it is referenced by other objects currently in use—is inherently a global property. This means that keeping track of object usage tempts you to breach the encapsulation and modularity of your program. There are several approaches you can use with Objective-C to help manage object lifecycles:
  • Manual memory management, using the free functions provided by the Objective-C runtime
  • Semi-automatic memory management, using root class reference-counting methods
  • Automatic memory management, using third-party garbage collector tools
The programming tools and libraries you use may constrain you toward or away from some strategies. For example, the Cocoa class library uses reference counting; if your code uses Cocoa objects it will have to be written to manage those objects with reference counting, even if your own objects use a different mechanism.
You can explicitly release the memory held by an object by calling its -free method (if it inherits from Object) or its -dealloc method (if it inherits from NSObject). It will be your responsibility to ensure that your program no longer needs the object.
In classes you write, the deallocation method should release any objects managed by the receiver, as well as any other kinds of resources (such as network sockets) the receiver holds. As with deciding to deallocate the receiver itself, it is your responsibility to ensure that your program no longer needs the objects the receiver will release. This is difficult enough that automatic management systems are becoming more prevalent.
The Cocoa framework supports reference counting: a technique that associates with an object a count that describes how many references there are to the object in other code. When this count is positive, the object is in use; when the count reaches zero the object can be discarded and its memory reclaimed.
The count doesn't specify the users of the object. When an object has a reference count of one it means
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Archiving Objects
Saving and restoring objects is made easier by Objective-C's facilities for reflection —inspecting at runtime the structure of instances and classes. Objects can be pre-designed at build-time, encoded, and saved as resources for reconstruction at runtime. The runtime state of objects can similarly be saved and restored in documents or other files. An object's values are stored along with type information necessary to restore a fully functioning instance.
To save and restore descendants of Object, you can use its methods -write : and -read :, along with some functions provided by the runtime and a helper class called TypedStream .
For example, suppose your class declares an interface like this:
@interface 
               MyClass : Object {
  AnotherClass* obj;
  int 
               i;
}
...
@end
To add the fields that MyClass declares to a stream that will be written to an archive, implement the following method:
1 -(id)write:(TypedStream*)stream { 
2   [super write:stream];
3   objc_write_types(stream, "@i", obj, &i);
4   return 
               self;
5 }
Line 1. Override the root class method -write:.
Line 2. Call the parent class method to write the fields declared in the parent.
Line 3. Call the runtime function objc_write_types( ) . The second parameter is a concatenation of descriptors for the types of fields you are writing. These are one-character strings, the same as those used by the @encode directive. They are listed in objc-api.h.
To read the fields of MyClass from a stream that has been read from an archive, implement the following method:
1 -(id)read:(TypedStream*)stream {
2   [super read:stream];
3   objc_read_types(stream, "@i", obj, &i);
4   return 
               self;
5 }
Line 1. Override the root class method -read:.
Line 2. Call the parent class method to read the fields declared in the parent.
Line 3. Call the runtime function objc_read_types( ) . The second parameter is a concatenation of descriptors for the types of the fields you are reading. These are one-character strings, the same as those used by the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Key-Value Coding
Objective-C lets you call methods specified by variables at runtime using the selector mechanism. Key-value coding is a library facility that puts field access on the same dynamic footing: you can access an object's fields by naming them. For example, you could use the following code to retrieve the parent field of a window object:
Window*parentWind = [wind valueForKey:@"parent"];
Because you can pass a string variable to -valueForKey : as well as a literal value, this is another way your program's behavior can vary based on values that aren't known until runtime.
NSObject implements -valueForKey: method as part of the NSKeyValueCoding category, which declares methods for reading from and writing to the fields of objects. These methods store and retrieve Objective-C objects, so their primary use is in accessing objects. However, even if your fields are integers or other numeric types, you can still use key-value coding to retrieve and set them. The methods will take NSNumber objects and automatically convert them to set numeric fields, and return NSNumber objects when you read numeric fields.
The key-value methods can bypass the access modifiers of the static language: you can read and write to private fields as easily as to public ones. This might seem like a violation of the object's declared interface. However, you can prevent key-value methods from bypassing your access modifiers by overriding +accessInstanceVariablesDirectly to return NO.
In addition, the key-value methods first search for an appropriate accessor method in your class before attempting to read from or write to a field directly. For example, the methods that read a field named field will look for accessor methods with the following names (the order will vary as described in the next section):
  • getField
  • field
  • _getField
  • _field
The key-value methods will take care of uppercasing the first letter of the field name before prepending get or
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Optimizing Method Calls
Objective-C's message-passing implementation of method calls is simple and flexible. What it sacrifices is the speed of a C++-style method call, or of a direct function call.
If you are writing time-critical code, you may want to relinquish the dynamic nature of the Objective-C method call for some extra speed. For example, if your code calls the same method on an object many times in a loop, you may not want to send a dynamic message each time you invoke the method. Objective-C provides a way for you to get a pointer to the function implementing the method, and then call the method via the pointer, bypassing the Objective-C method dispatch process.
If you only call a method once, you should use a standard Objective-C method call. This optimization's gain in efficiency is directly related to the number of times you invoke the method.
For example, suppose you want to send the following message to invoke a method that takes an integer and has no return value:
[obj 
            methodName:anInt];
You can replace this ordinary Objective-C method call with the following code:
1SEL 
            sel = @selector(methodName:);
2 typedef void (*MpType) (id, SEL, int);
3 MpType 
            mptr = (MpType) [obj methodFor:sel];
4 ...
5 mptr(obj, sel, anInt);
Line 1. Get the selector for the method you want to call. You will use this both to acquire the method pointer and to use it.
Line 2. Define the type of your method pointer. This makes line 3 easier to read. Recall that methods are just C functions with two hidden parameters: the receiver and the selector. Here, the type of mptr takes these into account, as well as the return (void) and parameter (int) types of the method.
Line 3. Get the function pointer. If you already have the receiver at hand (as in this example) you can use -methodFor : (for descendants of Object) or -methodForSelector : (for descendants of NSObject). If you don't have the receiver or an object of the same type, you can call the class methods
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Objective-C++
gcc is at once a compiler for C, Objective-C, and C++. You can intermix C++ and Objective-C code to some degree. To instruct the compiler that a file contains C++ code as well as Objective-C, use the file extension .mm or .M instead of .m.
Following are some ways in which C++ and Objective-C code can be used together:
  • Objective-C objects can have fields that point to C++ objects, and vice versa.
  • Objective-C code can call methods on C++ objects, and vice versa.
  • Objective-C objects can have C++ objects (as opposed to pointers) as fields, but only if the C++ class has no virtual methods.
However, Objective-C and C++ are not completely compatible. Here are some things you can't do:
  • Objective-C classes can't inherit from C++ classes, and vice versa.
  • You can't declare Objective-C classes in C++ namespaces or templates, or vice versa.
  • You can't use C++ keywords for Objective-C variable names.
  • You can't call Objective-C methods with C++ syntax, or vice versa.
Finally, there are some restrictions that are imposed to avoid ambiguity:
  • You can't use the name id as a C++ template name. If you could, the declaration id< TypeName > var could be either a C++ template declaration or an Objective-C declaration using a protocol.
  • If you are passing a globally-scoped C++ variable to an Objective-C method, you need a space between the first and second colons. For example:
    [obj 
                      methodName: ::aGlobal].
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Objective-C Resources
If you want to learn more about Objective-C, your options are more numerous than ever. Following are some text and Internet resources that expand on the topics outlined in this handbook.
http://www.ora.com/catalog/objectcpr
Updates and corrections to this handbook.
http://www.faqs.org/faqs/computer-lang/Objective-C/faq/
Frequently asked questions about Objective-C, and their answers.
http://developer.apple.com/techpubs/macosx/Cocoa/ObjectiveC/ObjC.pdf
A document summarizing the Objective-C language, and providing examples of its use with the Cocoa libraries.
news://comp.lang.objective-c
Usenet newsgroup for discussing Objective-C.
http://www.cetus-links.org/oo_objective_c.html
Many helpful links to FAQs, tutorials, and other information about Objective-C.
http://gcc.gnu.org
Web site for releases and documentation for GNU's gcc compiler.
http://developer.apple.com/techpubs/macosx/Cocoa/CocoaTopics.html
Web site for documentation of the Cocoa class library.
http://www.gnustep.org
Web site for releases and documentation for the GNUstep library, an open source version of Cocoa.
http://cocoa.mamasam.com
A searchable archive that combines several Cocoa developer mailing lists.
Cocoa Programming for Mac OS X
An introduction to both Objective-C and the Cocoa framework. By Aaron Hillegass. Addison-Wesley.
Learning Cocoa with Objective-C
An introduction to both Objective-C and the Cocoa framework. By James Duncan Davidson. O'Reilly & Associates.
Cocoa Programming
A more advanced guide to the Cocoa framework. By Scott Anguish, Erik Buck, and Donald A. Yacktman. SAMS.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!

Return to Objective-C Pocket Reference