Class Declaration
Objective-C classes typically include an interface .h and an implementation .m pair of files. The .h file contains property and method declarations. The .m file contains method implementations.
Example .h interface file
Example .m implementation file
Inheritance
Class inheritance is specified in the .h interface file with the syntax: @interface <MyClass> : <ParentClass>. The following example tells the compiler that the Employee class inherits from (extends) the Person class.
![Hot Tip](/storage/rc-covers/5126-thumb.png)
Interfaces
Objective-C interfaces are created using the @protocol declaration. Any class can implement multiple interfaces. Interfaces are typically declared in a .h header file and can be included via #import statements in the .h header file of other classes.
Primitive Data Types
As a superset of ANSI C, Objective-C supports its same primitive data types.
intIntegral numbers without decimal pointsfloatNumbers with decimal pointsdoubleSame as float with twice the accuracy or sizecharStore a single character such as the letter ‘a’BOOLBoolean values with the constants YES or NO
Common Object Data Types
NSObjectRoot class of the object hierarchyNSStringString valueNSArrayCollection of elements, fixed size, may include duplicatesNSMutableArrayVariable sized arrayNSDictionaryKey-value pair collectionNSMutableDictionaryVariable sized key-value pair collectionNSSetUnordered collection of distinct elementsNSDataByte bufferNSURLURL resource
Instance Variables
Class instance variables are declared within a curly braced {} section of the .h file.
Notice that the object variable declarations are preceded by * symbol. This indicates that the reference is a pointer to an object and is required for all object variable declarations.
Dynamic Typing
Objective-C supports dynamic typing via the id keyword.
Methods
Methods are declared in the .h header file and implemented in the .m implementation file.
Method Declaration Syntax
![Method Declaration Syntax](/storage/rc-covers/5127-thumb.png)
Method Invocation Syntax
Method invocations are written using square bracket [] notation.
![Method Invocation Syntax](/storage/rc-covers/5128-thumb.png)
Using Dot Notation Method Invocation
Objective-C 2.0 added the ability to invoke property accessor methods (getters/setters) using “.” notation.
Multi Parameter Methods
Multi-Parameter methods are more verbose than other languages. Each parameter includes both an external name, data type, and a local variable name. The external parameter name becomes a formal part of the method name.
Self and Super Properties
Objective-C objects include a self property and a super property. These properties are mutable and can be assigned in an advanced technique called “swizzling”. Most commonly, the self attribute is used to execute a method on the enclosing object.
Properties Using @property and @synthesize
Objective-C 2.0 added property declaration syntax in order to reduce verbose coding of getter and setter methods.
Multiple variables may be included in a single @synthesize declaration. Alternatively, a class may include multiple @synthesize declarations.
@property Attributes
Property attributes specify behaviors of generated getter and setter methods. Attribute declarations are placed in parenthesis () after the @property declaration. The most common values used are (retain, nonatomic). retain indicates that the [retain] method should be called on the newly assigned value object. See the memory management section for further explanation. nonatomic indicates that the assignment operation does not check for thread access protection, which may be necessary in multi-threaded environments. readonly may be specified to indicate the property’s value can not be set.
Object Initialization
Object instances are created in two steps. First, with a call to alloc and second, with a call to init.
In order to perform specific object initialization steps, you will often implement the init or an initWith method. Notice the syntax used around the self property in the following example. This is a standard init pattern found in Objective-C. Also notice the method uses a dynamic id return type.
Class Constructors
Classes often include constructor methods as a convenience. The method type is + to indicate that it is a class (static) method.
#import Statements
#import statements are required to declare the classes and frameworks used by your class. #import statements can be included at the top of both .h header and .m implementation files.
Control Flow
Strings
Objective-C string literals are prefixed with an “@” symbol (e.g. @”Hello World”). This creates instances of the NSString class; instead of C language CFStrings.
NSLog / NSString Formatters
Formatters are character sequences used for variable substitution in strings.
Data Structures
Using NSArray
Using NSDictionary
Memory Management
Objective-C 2.0 includes garbage collection. However, garbage collection is not available for iOS apps. iOS apps must manage memory by following a set of object ownership rules. Each object has a retain count which indicates the number of objects with an ownership interest in that object. Ownership of an object is automatically taken when you call a method beginning with alloc, prefixed with new, or containing copy. Ownership is manually expressed by calling the retain method. You relinquish object ownership by calling release or autorelease.
When an object is created it has a retain count of 1 When the “retain” message is sent to an object, the retain count is incremented by 1 When the “release” message is sent to an object, the retain count is decremented by 1 When the retain count reaches 0, it is deallocated
dealloc Method
When an object’s retain count reaches 0, it is sent a dealloc message. You will provide implementations of the dealloc method, which will call release on the instances retained variables. Do not call dealloc directly.
Autorelease Pools
An autorelease pool (NSAutoreleasePool) contains references to objects that have received an autorelease message. When the autorelease pool is deallocated, it sends a release message to all objects in the pool. Using an autorelease pool may simplify memory management; however, it is less fine grained and may allow an application to hold onto more memory than it really needs. Be watchful of which types and size of objects you use with autorelease.
Categories
Categories are a powerful language feature which allows you to add methods to an existing class without subclassing. Categories are useful to extend the features of existing classes and to split the implementation of large classes into several files. Categories are not subclasses. Generally, do not use methods in a category to extend existing methods except when you wish to globally erase and redefine the original method. Categories can not add instance variables to a class.
Selectors
Selectors create method identifiers using the SEL datatype. A value can be assigned to a SEL typed variable via the @selector() directive. Selectors, along with NSObject’s method performSelector: withObject: enable a class to choose the desired message to be invoked at runtime.
Working With Files
iOS applications have access to files in an app-specific home directory. This directory is a sand-boxed portion of the file system. An app can read and write files within this its own hierarchy, but it can not access any files outside of it.