Showing posts with label iPhone guide. Show all posts
Showing posts with label iPhone guide. Show all posts

Tuesday, 27 December 2016

Objective-C Guide For Developers: Part 5

This article, part 5 covers:
Defining custom types
Constants and enumerations
Bitwise operators and bitmasks
Structures

Defining custom types

We have already seen in the previous parts of this guide that there are two kinds of types a variable can have in Objective-C: basic types, as we have seen in the first part of this guide or object types, coming from classes either defined in Apple frameworks or defined by us. We have spent the last issues seeing how to create and extend the latter, but what about basic types? Can we define them too? If so, why would this be useful since we already have classes?
It turns out, of course, that we can indeed define new basic types, and actually we have already met some of these newly defined types, although I didn’t mention what they were. The C language basically offers only basic types for integers and floating point values. As we have seen, even the bool and char types are in the end just integers used in a different manner (and with a different byte size in memory, to be precise).
C, unlikely other languages like Java, allows also the definition of new basic types, the only condition being that these new types must be derived from the ones already provided by the language (or by composing them, as we will see later). In fact, the Objective-C basic types we encountered, like NSInteger or CGFloat, are just redefinitions of basic C types, namely long and double, respectively.
Why this redefinition? Could we not just use long and double instead? Of course we could, but there are some advantages in defining new types. The first one is clarity and legibility. CGFloat is not the only redefinition of the doubletype, there are also others, like NSTimeInterval. Despite being both the same type of value in memory, in our code we can clearly see that a variable of the first type represents graphical values, like coordinates on screen or sizes of graphical objects, while a variable of the second type represent an amount of time (in seconds, as defined by the documentation).
The other reason is one we already encountered, which is to differentiate the actual memory representation of a type based on the architecture in a way that is transparent to the developer. I said that a CGFloat is just a double, but actually that is not entirely correct: it’s a double on 64 bits architectures, while it’s a float on 32 bits ones. This redefinition allows the redefinition of the underlying representation of the types when needed, without requiring to change all the code that has been written up to that point (and this is exactly what happened to NSInteger and CGFloat in the transition from 32 to 64 bits architectures).
Now that we know the reasons to define new types, here is how to do it:
typedef existingType newType;
So, for example, if I want to define a type to represent people’s age as a positive integer, I can write:
typedef unsigned int Age;
or alternatively:
typedef NSUInteger Age;
I can then use this new type normally to define variables or properties in objects. Let’s rewrite our previous example of the Person class to include an age property:
typedef unsigned int Age;

@interface Person : NSObject

@property NSString *firstName;
@property NSString *lastName;
@property Age age;

@end

Constants and enumerations

Sometimes we need variables to be constant and to not change their value over time. This is easily done with the constkeyword in front of a variable declaration:
const double Pi = 3.14159;
The compiler will make sure that the content of this variable is never changed and will emit an error if you try to assign a new value to it after this declaration.
(By the way, if you need pi it’s already defined as the M_PI constant, together with other common mathematical constants in the header file math.h, which is always available in C, so you don’t have to include it directly in your source files).
Sometimes though we need to define more constants to enumerate different options we might have and we don’t really care about the values these constants might have as long as they are different from each other (sometimes we might need these values to be ordered).
Let’s say we want to add a sex property to our Person class. The only values we want to allow are Male, Female and Undefined when sex is not specified (for simplicity of the example I will not include the various transgender identities, but when you deal with such kind of data in real like it’s helpful to not make the assumption that people only identify themselves with the two canonical sexes).
We could already use the const keyword for this and define each sex as an integer constant with values 0, 1 and 2. This would work but would be impractical for larger sets of constants, because when we needed to introduce a new value inside the order, we will have to change all the other values manuallyt. Luckily C has a special construct made for this, called enum, which stands for enumeration:
enum {
    FirstConstant,
    SecondConstant,
    ...
    LastConstant
};
In this way all the constants get consecutive values starting from 0. Notice that the last constant does not have a comma after it and there is a semicolon after the closing brace (these are two common mistakes that cause syntax errors). It’s also possible to start from a value different than 0:
enum {
    FirstConstant = number,
    SecondConstant,
    ...
    LastConstant
};
The consecutive constants will get incremental values starting from the selected number. It is even possible to assign an arbitrary value to each constant, if needed.
It does not stop here. It’s possible to use an enumeration to define a new type:
typedef enum {
    FirstConstant,
    SecondConstant,
    ...
    LastConstant
} TypeName;
Where the name of the type goes at the end, after the closing brace. Since iOS 6 and Mac OS 10.8, Apple introduces a new NS_ENUM macro, which is now the preferred way to define enumerations. I included the other ways in this guide for completeness, since you might still find them in some code bases or in Apple documentation, but you should use NS_ENUM for your enumerations:
typedef NS_ENUM(baseType, newTypeName) {
    FirstConstant,
    SecondConstant,
    ...
    LastConstant
};
This macro adds a baseType to ensure a fixed size for the newly defined type. It  also provides hints to the compiler for type-checking and switch statement completeness. It’s also a bit more readable since the new type name is at the top and not at the bottom.
We can now expand our Person class to include sex:
typedef unsigned int Age;

typedef NS_ENUM(NSUInteger, Sex) {
    Undefined,
    Male,
    Female
};

@interface Person : NSObject

@property NSString *firstName;
@property NSString *lastName;
@property Age age;
@property Sex sex;

@end
I put the Undefined constant at the beginning, so it will have a value of 0 which is the default value properties have when an object is created. We can then use the constants when creating our object:
Person *person = [Person new];
person.firstName = @“Matteo”;
person.lastName = @“Manferdini”;
person.age = 33;
person.sex = Male;
Pay attention though that the compiler does not enforce the values that we can assign to a variable with an enumeration type. So this will still compile and run perfectly fine:
person.sex = 7;
Apple makes extensive uses of enumerations in its classes. For example, to create a new button in iOS 7, you would use the +buttonWithType: factory method with a UIButtonTypeSystem type:
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];

Bitwise operators and bitmasks

There is still a class of operators I didn’t mention over when I spoke about operators in Objective-C: bitwise operators. They are used for bitwise operations as the name implies, which are usually needed for some low level implementations (like network protocols), but can be used also for other purposes as we will now see. Like the other operators, these ones come directly from C. This is a table summing them up:

Operator  Description       Syntax

&   bitwise and       a & b
|    bitwise or       a | b
^    bitwise xor       a ^ b
<<    left shift       a << b
>>    right shift       a >> b
~    bitwise not, or one’s complement    ~a
Let’s see how they are usually used in Objective-C. With enumerations we have seen how we can create types that allow us to name different constants in a more readable way. The limitation with enumerations, though, is that a variable can only have one of the defined values at a time. What if we want to have a predefined set of options that are not mutually exclusive but can be set at the same time?
One way of doing this would be again to create a class with a boolean property for each option we want to enable simultaneously, but this would be an overkill and we would need to then assign or check every property singularly, making it very tedious to check all the options.
This special case can be handled easily with bitwise operators. We can make each constant in the enumeration have only one bit set to 1 and all others set to 0 (remember that we can assign an arbitrary value to an enumeration). Then, to specify multiple options at the same time we can use the bitwise or operator to group them in the same variable. Lets see how this works with an example.
Let’s say we want to have 4 non mutually exclusive options. We can declare an enumeration with bitmasks using the left shift operator. As we had the NS_ENUM macro for normal enumerations, we have the NS_OPTIONS macro for bitmask enumerations (but a simple typedef enum would still work, of course):
typedef NS_OPTIONS(NSUInteger, Options) {
    NoOptions = 0,
    Option1 =   1 << 0,
    Option2 =   1 << 1,
    Option3 =   1 << 2,
    Option4 =   1 << 3,
} Options;
The options will have the following bit representations in memory (I will omit leading zeros for clarity and only show the last 4 bits):
Option      Value

NoOptions   0000
Option1     0001
Option2     0010
Option3     0100
Option4     1000
When we want to group multiple options in the same variable, we can use the bitwise or operator:
Options enabledOptions = Option1 | Option3;
This groups the multiple options together in this way:
Option1          0001
Option3          0100
                 ----
enabledOptions   0101
As you can see, both the first and the third bit (from the right) are set in the enabledOptions variable, thus containing both values. To check wether any option is enabled we can use the bitwise and operator:
if (enabledOptions & Option1) {
    ...
}
If an option is enabled, operating a bitwise and on the value will produce a non zero value, that can be used as a true value in a condition. A bitwise and with a non enabled option produces a value of zero, which is equivalent to false.
You can use this in your code and Apple indeed does use it in different places. If we want to specify, for example, an autoresizing mask for a view with both flexible width and height, we can do it this way:
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | 
                        UIViewAutoresizingFlexibleHeight;

Structures

Now, what if we want a variable to hold more than one value? One possibility is of course to create an object for that, as we have already seen, and in many languages this is the only option to achieve this purpose. But Objective-C inherits a feature from C that allows variables to contain more than one value, without being an object: structures.
You rarely need to create structures in your apps, but if you need something more lightweight than an object to contain simple values and with faster access a struct might be your tool. A structure is just a some space in memory that contains some values exactly as variables do, so it does not incur in the additional overhead of objects. A structure variable is declared with the keyword struct and can contain as many values as you want:
struct variableName {
    type memberName;
    ...
};
The syntax is similar to that of enumerations, but notice that here there is a semicolon after each member of the structure, because they act like variable declarations inside of the structure.
Let’s say, for example, that you want to store the value of a point on screen, which is identified by x and y coordinates. You can do so with a structure:
struct point {
    CGFloat x;
    CGFloat y;
};
You can then access the members with dot notation:
point.x = 100.0;
point.y = 200.0;
Or you can initialize the whole structure in one line using the following syntax with curly braces:
 point = {100.0, 200.0};
As happens for enumerations, you can turn structures into basic types to be able to reuse them:
typedef struct {
    type memberName;
    ...
} typeName;
This is exactly how the CGPoint type is declared, for example. CGPoint is used to store coordinates of graphical objects in iOS apps.
A disadvantage of structures over objects is that functionality needs to be defined externally. After all structures are only a basic type and cannot have methods attached. This requires you to write C functions to operate on them, which you usually don’t want to do. For example, CGPoint has a function to initialize a new structure:
CGPoint point = CGPointMake(100.0, 200.0);
or a function to compare two points:
if (CGPointEqualToPoint(point1, point2) {
    ...
}
Structures can also contain other structures, as in CGFrame, a type that indicated rectangles of graphical objects. A CGFrame has a origin, which is a CGPoint, and a size expressed in width and height, which is a CGSize. Under ARC, though, a structure cannot contain objects, so a structure can only be composed from other basic types.
These are structures you will encounter quite often, with other structures (like CGAffineTransform, for example, if you want to rotate, scale or translate graphical objects). There are a lot of functions in Apple frameworks to deal with these structures, but as you can see, this separates the functionality from the data, which defeats the Object Oriented Paradigm. For this reason it’s usually better to create a new class instead of a structure for your values, unless you have specific reasons like compatibility with C or C++ code, or to optimize execution speed.

Objective-C Guide For Developers: Part 4

This Article, Part 4 of the Beginners iOS Development: Objective-C Guide for Developers series covers:
Categories
Protocols
ARC and memory management

Categories

Objective-C has a very powerful and useful feature that many other languages miss: categories. It’s a good programming practice to keep the inheritance hierarchy as shallow as possible, since inheritance it introduces complexity when overriding methods. The common way to do this is to use composition (objects that use other objects) and leave inheritance to cases where it’s necessary. For example, instead of subclassing NSArray, it’s better to write a class that uses a NSArrayinstance internally. Objective-C though offers another alternative to composition through categories, that allow you to add methods to existing classes.
This includes any class, so it means you can also add methods to classes from external frameworks, including the ones provided by Apple. This is very powerful because it does not only mean that you don’t need to subclass a class to add behavior to it, but also that the methods you add will be available to its subclasses, which you would not be able to do through subclassing. Moreover you can alter instances used internally by other classes. For example, UIViewControllerobjects create their own UIView instance if you don’t provide one, or UILabel objects have their own instance of the UIFont class. With categories, your methods will also be available to these instances created by classes you don’t own.
The category declaration uses the @interface keyword like the class declaration but does not indicate any inheritance. Instead, it specifies the name of the category in parentheses:
@interface ClassName (CategoryName)

@end
A category then has an @implementation section like a normal class, where you put the additional method implementations:
@implementation ClassName (CategoryName)

@end
A category usually has a .h and .m files like normal classes. The file names are created with by the name of the class and the name of the category separated by a +, in the form ClassName+Category.h (or .m).
At runtime, there’s no difference between a method added by a category and one that is implemented by the original class.
Let’s say for example that we want to add a method to NSString to know if a string starts with a capital letter. The declaration of the category would be as follows:
@interface NSString (Capitals)

- (BOOL)startsWithACapitalLetter;

@end
And this the implementation:
#import "NSString+Capitals.h"

@interface NSString (Capitals)

- (BOOL)startsWithACapitalLetter {
    unichar firstCharacter = [self characterAtIndex:0];
    return [[NSCharacterSet uppercaseLetterCharacterSet] 
        characterIsMember:firstCharacter];
}

@end
You can then call this method on any NSString instance, even those coming from literals:
NSString *myCapitalizedString = @"This string starts with a capital letter";
if ([myCapitalizedString startsWithACapitalLetter]) {
    ...
}
Categories can add methods to classes, but not instance variables. So if you need to add functionality to a class that requires storing some value, the only option you have is to create a new subclass.
In the case of properties we have a partial behavior: as we have seen in Objective-C properties add new accessors methods to a class. This works in categories too, so a category can declare new properties for a class. But a category cannot add new instance variables to a class and this still holds true for properties. This means that properties added through a category are not backed up by instance variables like normal properties are. So, when you add properties through a category, you always have to provide your accessors since the compiler will not synthesize them for you. Moreover they can only reference existing instance variables.
Pay attention not to override existing methods in categories. Although I’ve seen some developers declare that this is fine, it’s not. As per Apple documentation, if there is a name clash with a method in a category, which one will be chosen at runtime is undefined, so you are never sure if your implementation is the one that is going to win. Categories are not a valid way to override methods.
To avoid name collisions when you declare a method on a class you don’t own, it’s best practice to prepend a prefix to the method name. In this case the prefix is lower case to respect conventions for method names and is usually separated with an underscore.

Interface extension

A special type of category is the class interface extension, also known as anonymous category. The interface extension can only be added to your own classes and the methods it declares are usually implemented in the class own @implementation block instead of a separate category implementation. An interface extension is declared without specifying the category name in the parentheses.
@interface ClassName ()

@end
What is special about it is that, unlike other categories, an interface extension can declare new instance variables and the properties it declares behave like properties declared directly in the class interface (they are backed up by instance variables and the accessor methods are automatically synthesized by the compiler).
Interface extensions are used to declare private information for a class. While other languages have a special keyword for this, Objective-C solves this problem with interface extensions. This allows to have partially private methods and properties for selected classes, by declaring the interface extension in a separate header file which is imported only by those classes. This is how Apple declares its own private API which is not available to other developers.

Protocols

Sometimes you need to declare a minimum interface that a class needs to implement to interact with another class. A class interface or a category declare methods that are specific to a class, while a protocol declares properties and methods that are independent and can be implemented in many different classes. Other languages have a similar feature to protocols (Java calls them interfaces, which might generate some confusion at first if you are a Java developer, since interfaces are a different thing in Objective-C). When a class conforms to a protocol, it must implement the required methods declared by it.
A very common example is the UITableView class. UITableView is a class found in iOS to display a vertically scrollable list of items. You stumbled upon one already if you use an iPhone or an iPad, since it’s omnipresent. Since UITableView is a generic class that is used to display many different kinds of lists, with diverse visualizations for the items, all this information needs to be provided to the table view by some other objects.
UITableView defines two protocols that declare what methods it expects two other classes, called the data source and the delegate, to implement to be able to retrieve the information it needs. Since the protocols are separated, the two classes can also be separated, but they are generally the same class.
The data source implements methods that tell the table view how many items and sections there should be and provides them when the table view asks for them to display them on screen. The delegate provides instead information on the visualization of these items, like the kind and size of views used to represent items (called cells).
Any class (usually implemented by you) can be the data source or delegate of a table view and to do so it needs to conform to these two protocols.
A protocol is declared with the @protocol keyword:
@protocol ProtocolName

@end
Inside the protocol interface you declare the methods that a conforming class needs to implement. It is possible to declare optional methods in a protocol that a conforming class can implement only if it needs to. You do so using the @optionaldirective in the protocol declaration:
@protocol ProtocolName

// list of required methods

@optional

// list of optional methods

@end
There is also a @required directive to switch back to declaring required methods, but it’s better not to switch back and forth for the readability of the protocol. If you mark some method as optional, you will have to check if the receiving object implements the method before calling it, or you will get an exception. You check this by using the respondsToSelector:method of NSObject (so it’s available to every class). This method takes a selector as a parameter, which you can obtain with the @selector() directive around a method name, in this way:
if (object respondsToSelector:@selector(someMethod))
    [object someMethod];
To indicate that a class conforms to a protocol, the protocol name is indicated in angular brackets in the class interface:
@interface ClassName : Superclass 

@end
A class can conform to multiple protocols, which are then comma separated inside of the angular brackets:
@interface ClassName : Superclass 

@end
The same syntax is used to declare that a variable or a property contains an object that must conform to one or more protocols:
id  variableName;
or:
@property id propertyName;
In this way the compiler will check that the object stored in the variable or property conforms to the protocol, helping to avoid programming errors.
Protocols can conform to other protocols, to include the methods declared in the latter. You specify this conformance in the same way you do for a class:
@protocol ProtocolName 

@end

ARC and memory management

The approaches to memory management you find in other languages are usually two: either memory management is completely left to the developer (like in C or C++) or is handled by a garbage collector (like in Java, C#, Python or Ruby).
In the first case developer has to know when to allocate and especially release memory “manually”, while avoiding to address memory that does not exist yet or releasing still used memory too soon. Both these tasks are tedious and error prone and might lead to crashes, unexpected behavior, or leaks that eventually fill up all the available memory.
In the case of the garbage collector, the developer abdicates the memory management to a process that periodically scans the memory and releases the one that is not used anymore. This relieves a lot of pain, so it has become the preferred way in modern languages, but still has some pitfalls. Since to know what parts of memory are used this the garbage collector looks at all the references in the object that are in memory at a given time, the developer has to pay attention not to create reference cycles between object, where two objects reference each other and the memory is not released even if those two object are not referenced anywhere else.
Objective-C comes from a history of semi automatic memory management. Apple used for a long time an in between approach, called reference counting. Reference counting works this way: whenever some objects needs to keep a reference to another object, it retains it. Retaining an object increases a count of references to the object by one. When the object is not needed anymore, object that retained it have to release it. Releasing decrements the count by one. When an objects reaches a retain count of 0, it gets removed from memory by the runtime.
Retaining and releasing are still responsibility of the developer and, if done wrong, they still lead to accessing deallocated memory (which usually causes crashes) or memory leaks. The benefit is that reference counting allows the developer to think about memory locally, asking when an object needs to retain another, instead of globally. This alleviates a lot the pain of manual memory management and paired with some common programming patterns was much safer and easier than manual memory management.
For a brief period Apple adopted garbage collection on Mac OS 10.6. But when the iPhone came out, the resources on the device were too limited to run a garbage collection process. One downside is that the garbage collector needs to be run periodically, while the program execution is halted to avoid problems with changing references. This is usually not perceived on a normal computer, but on a phone with limited resources it freezes apps for some time, leading to a bad user experience. Another downside is that allocated memory of the program keeps accumulating until the garbage collector is activated, which is again a problem on a device with very limited amount of memory. For this reason, when the iOS SDK was released, Apple switched back to reference counting.
In modern Objective-C, memory management is done through what is called ARC. Reference counting is still supported for old legacy code, but since ARC works back to iOS 4 and Mac OS 10.7, reference counting should not be needed anymore and we will not have a look to how it works.
So, what is ARC? As I said, reference counting is led by common patterns and best practices on when retain and release should be performed and how to name methods that involve reference counting. For this reason Apple saw an opportunity to automate it and introduced Automatic Reference Counting, or ARC.
ARC removes reference counting from the developer hands and automates it in the compiler. The benefit is that, in addition to taking away responsibility for tedious memory management from the programmer, ARC is done at compile time, when the binary of the app is created, thus removing any runtime process that might slow down the device. What the compiler actually does is to add the proper memory retain and release calls in the code where they are needed.
ARC has been highly optimized, so it works generally faster than the memory management done manually. Moreover it forces some memory checks into the compiler, which then signals problems to the developer to be fixed, or the app won’t compile, removing many memory management errors. Since at this point in time ARC is supported on the vast majority of machines and devices, it is advise to migrate all code bases, so probably you will never have to learn manual reference counting. XCode has a tool to automate this transition as much as possible.
ARC still suffers from one pitfall though, as garbage collection does. If an object circular references exists, a retain cycle is created and the memory used by the object will never be released, exactly how it happens in garbage collected languages.
To avoid retain cycles, Objective-C has some lifetime qualifiers. For properties, two qualifiers exist: strong and weak. The default qualifier is strong, which signals that the reference object needs to be kept in memory until that reference exists. Thus, the standard declaration we saw for properties
@property Class *propertyName;
is the same as
@property (strong) Class *propertyName;
If you need to create a reference cycle to make two (or more) objects communicate with each other in a circular manner, one of the two needs to have weak reference to the other one. This is used a lot, for example, in the delegate design pattern, a very common pattern in Objective-C. To avoid a retain cycle, one of the classes still uses a strong property:
@interface ClassA : NSObject

@property ClassB *objectB;

@end
while the other uses a weak one:
@interface ClassB : NSObject

@property (weak) ClassA *objectA;

@end
When nothing references the objectA anymore, it is removed from memory because the weak reference does not count when counting references. So objectA is not retained by objectB, making it possible to release objectA when it’s not referenced anymore by other objects. When objectA gone, the strong reference to objectB is removed, thus removing objectB too (if it’s not referenced strongly from anywhere else). When an object referenced weakly is removed from memory, all the weak references pointing to it are automatically set to nil, making it safe for the referencing objects to still call methods on it.
When using normal variables or instance variables, the corresponding lifetime qualifiers are __strong and __weak. As per Apple documentation, the qualifier needs to be specified after the * in the declaration, with this syntax:
NSArray * __weak array;
Although the documentation says that the compiler “forgives” other variants, it’s better not to use them since you never know when in the future the compiler won’t be so kind anymore.
Pay attention to __weak variables. When there is no other reference to the object they store they get immediately allocated leading to this common problem:
NSMutableArray * __weak strings = [NSMutableArray new];
[strings addObject:@"Hello"]; // On this line strings is already nil
On the second line, the strings array does not exist anymore and the variable will be nil already. This is because, even if the second line references it, there is no other strong reference to the array when it is created, therefore the compiler deallocates it immediately. Other subtle cases might be not so easy to spot, so pay attention when using __weak variables.
There are two more qualifiers for variables: __unsafe_unretained and __autoreleasing. The first one works like __weak, but the variable is not set to nil when the object it references is deallocated. For this reason it’s unsafe (as the name implies) because it leaves a “dangling” reference to deallocated memory. This leads to crashes if you try to call a method on it, unlike nil, which is safe. This identifier exists only to support ARC in iOS 4 and Mac OS 10.6, so you probably will never need it. If you inherit old codebases, pay attention also to the assign qualifier for properties, if you find any, because that’s equivalent to __unsafe_unretained. Change it to weak.
The __autoreleasing qualifier is used in parameters of methods passed by reference, which we will see later.

Objective-C Guide For Developers: Part 3

This Article, Part 3 of the Beginners iOS Development: Objective-C Guide for Developers series covers:
Classes
Headers, importing and forward declarations
Properties and instance variables
Initialization

Classes

The declaration and the implementation of a class are separated in Objective-C. To declare a new class we first declare the interface using the @interface directive:
@interface ClassName : SuperClass

@end
By convention, class (and type) names start with a capital letter (and don’t forget prefixes as we discussed before. I will omit them in the examples here for clarity, but I advise you to follow the conventions when writing your code).
After the colon the superclass from which our class inherits must be specified. The root class in Objective-C is NSObject. When one object encounters another object, it expects to be able to interact using at least the basic behavior defined by the NSObject class. NSObject offers a lot of basic behaviors like the +alloc and -init methods we have seen in the paragraph about creating objects.
The implementation of the class goes, intuitively enough, in the @implementation part:
@implementation ClassName

@end
Methods are declared in the @interface of the class:
@interface MyClass : NSObject

- (void)doSomething;

@end
and get implemented in the @implementation part. The implementation of the method goes inside curly braces:
@implementation MyClass

- (void)doSomething {
    ...
}

@end
When an object needs to send a message to itself, you can do so from within a method by using the self keyword.
- (void)someMethod {
    ...
    [self someOtherMethod];
    ...
}
To instead access the implementation of a method in the superclass (when you, for example, override one of its methods) you use the super keyword:
- (void)someMethod {
    ...
    [super someMethod];
    ...
}

Headers, importing and forward declarations

In Objective-C the interface and the implementation of a class are usually kept in two different files, unlike other languages where everything is kept in a single file. The interface goes in a header file with .h extension, while the implementation goes in a file with .m extension.
It is possible to declare interface and implementation of classes in only the .m file, which can contain more than one class. This is used if you want to declare an internal class that is used only in a single class implementation and not anywhere else. While some other languages have special constructs for this, in Objective-C you accomplish it by just putting the new class in the implementation file.
To reference class header files, Objective-C uses the #import directive. Always use this instead of the #include coming from C, also if you are importing C files, because #import will check automatically for double inclusion of headers so you will never have problems with recursive inclusion. #import uses angular brackets < > for global inclusions and double quotation marks ” “ for local ones. So if you are including a framework you do it like this:
#import 
while for your own classes in the project:
#import "MyClass.h"
Sometimes you need to have circular dependencies in some classes, where a class A needs a class B, and B needs A.
@interface ClassA : NSObject

- (ClassB *)methodThatReturnsAnInstanceOfClassB;

@end

@interface ClassB : NSObject

- (ClassA *)methodThatReturnsAnInstanceOfClassA;

@end
This code cannot compile, because ClassA needs to know about ClassB, which at that point still has not been declared. This happens also with Objective-C protocols, as we will see later in this guide. You can use a forward declaration to avoid this problem, with the @class keyword:
@class ClassB;

@interface ClassA : NSObject

- (ClassB *)methodThatReturnsAnInstanceOfClassB;

@end

@interface ClassB : NSObject

- (ClassA *)methodThatReturnsAnInstanceOfClassA;

@end
Forward declarations are often used in header files also to avoid importing the header of another class, which would import all the declarations present in the latter (classes, protocols, categories, types and constants) which, in turn, would also spread in all the files that import the header that includes it.

Properties and instance variables


We now need to know how to store the internal state of an object. It is a best practice in Objective-C to use properties for this purpose, which are declared in the interface of the class.
@property Type propertyName
Let’s use the typical example for an class: the Person class. If we want to declare a class to stores the first and last name of people, as well as their age, this would be its declaration:
@interface Person : NSObject

@property NSString *firstName;
@property NSString *lastName;
@property NSUInteger age;

@end
We can now use the dot syntax present in many languages to read or assign values to properties:
Person *person = [Person new];
person.name = @"Matteo";
When you declare a property, there are many things happening behind the scene. In the first place, a corresponding instance variable is automatically synthesized by the compiler for each property you declare to store the value of the property. Although it’s best practice to access the properties through the dot syntax, you might want to access these instance variables directly (for example, as we will see, to change a readonly property, in initializers, deallocation or custom accessors, or to avoid triggering key-value coding notifications). The name of the synthesized instance variable is the name of the corresponding property prefixed with an underscore.
(void)someMethod {
    _firstName = @"Some other name";
}
You can change the name of the instance variable sinthesized for a property if you want, declaring it explicitly with the @synthesize keyword in the class @implementation section:
@implementation ClassName

@synthesize propertyName = differentInstanceVariableName;

...
@end
For example, we can rename the instance variables in our Person class
@implementation Person

@synthesize firstName = ivar_firstName;
...
@end
You can also declare your own instance variables without a relative property. You can do so either in the interface of a class, to make these variables visible to subclasses:
@interface ClassName : SuperClass {
    Type _myInstanceVariable;
}
...
@end
or in the implementation of the class:
@implementation ClassName {
    Type *_myInstanceVariable;
}
...
@end

Accessors methods

Another thing that happens behind the curtains when declaring properties is that the compiler synthesizes automatically corresponding accessors methods. Objective-C is not like other languages where properties access directly the memory where the value for a property is stored. What happens instead is that every time you use a property with the dot syntax, that is translated into the corresponding method and a message is sent to the object, in the exact same way as if you were calling a method.
The method used to access the value, called the getter method, has the same name as the property. The method used to set the value, called the setter method, instead starts with the word “set” and then uses the capitalized property name.
So, in our Person class, when we declare the firstName property, these two methods are added to the class:
- (NSString *)firstName;
- (void)setFirstName:(NSString *)firstName;
You can use these methods yourself to read and write the value of the property, which is what happens anyway when you use the dot notation.
Because of this automatic translation I have seen some developers mistake some method call for a property, and also XCode (the IDE used to develop for iOS and Mac OS X) will autocomplete it anyway. I’ve seen this a lot, for example, with the count method of arrays.
NSUInteger numberOfItemsInTheArray = someArray.count;
The NSArray class has no property called count, but only a method. But this line of code will work anyway because of how properties work in Objective-C. The correct syntax would be:
NSUInteger numberOfItemsInTheArray = [someArray count];
Which is more consistent because the former implies the existence of a property that does not exists.
The accessor methods are synthesized automatically by the compiler, but you can provide your own ones if you want. This is one of the cases I mentioned where you actually need to access the instance variables behind properties directly.
For getter methods a common implementation is:
- (Type)property {
    return _property;
}
And for setter methods:
(void)setProperty:(Type)property {
    _property = property;
}
These are basic implementation that only read and write values of a property, but you might want to start from here to add further behavior to the accessors.
Pay attention that if you implement both the accessor methods for a property yourself, the compiler will assume that you are taking control of the property and won’t synthesize the instance variable for you. If you still need it, you need to declare it yourself in the class implementation:
@synthesize property = _property;
Sometimes you might want to declare a property as readonly. This happens when you create a property that is derived from other values and cannot be set, or simply when you want to have immutable objects or properties not changeable from an external object. If, for example we want to add a fullName property to our Person class, composed by the first name followed by the last name, we will declare this property as readonly:
@property (readonly) NSString *fullName;
We then need to provide a custom accessor method for it:
- (NSString *)fullName {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}
For readonly properties, providing the getter method is enough to prevent the compiler from synthesizing a corresponding instance variable.
The opposite of readonly is readwrite. Usually there’s no need to specify the readwrite attribute explicitly, because it is the default, but there is one case in which you might want to do it anyway. Sometimes you might want to declare a property as readonly for external objects only, but still be able to change its value from inside the object itself. You can do so by accessing the instance variable directly, but you might prefer to still use the property internally, for example to trigger Key-Value Coding notifications (which we will see later). In that case you can declare the property as readonly in the interface of the class and then redeclare it as readwrite in the interface extension, which we will see later.

Initialization

As we have seen previously, while other languages have constructs to create and initialize object, in Objective-C an object is created with the +alloc method and initialized though an initializer, often the -init method or another initializer that takes some parameters needed at the object creation moment.
All initializers in Objective-C start with the init word and have a return type id. As a rule an initializer should always be called in a nested call with the +alloc method:
MyClass *object = [[MyClass alloc] init];
This is done because the initializer might not return the same object that was created with the +alloc method. There are different reasons for this to happen: a class might be a singleton, thus allowing only one instance of it to exist at any time. In this case an init method will return that instance, if it already exists, discarding the one coming from +alloc.
If an initializer takes some unique identifier as a parameter, the init method might retrieve that object if it exists and return it, again discarding the one created with +alloc. This is not a singleton, since many instances of the class are allowed, but still specific instances are unique.
When you are writing your own classes it’s very likely that you need to implement your own initializers to setup your objects properly. If you don’t need any parameter when initializing an instance, you simply override the -init method inherited from NSObject:
- (id)init {
    if (!self = [super init])
        return nil;

    ... // Instance variables are set here
    return self;
}
The first thing you need to do when implementing an initializer, is to call the initializer of the superclass first. If the result is nil, it means that something went wrong with the initialization and you have to return nil yourself.
You might have notice that in the condition of the if the result of the initializer of the superclass is assigned to self. This is again for the same reason: that method might return a different instance, substituting the current one.
The assignment in the if condition is actually a syntax that is allowed by C. In C the assignment operator also returns the value that gets assigned, so it can be tested in an condition. I personally consider it a bad programming practice, because it does two things at the same time, hiding one of them (the assignment) and making it a side effect. This is the source of many programming errors, where some developer that wants to check for equality uses the = operator by mistake instead of the == operator. If you actually make yours the practice of testing assignments directly this kind of errors will be even harder to spot, since they will become invisible to your eyes.
This said, it is idiomatic to do this in an initializer in Objective-C, so I consider this case, and only this case, acceptable. My advice is to avoid it in all other cases.
After the call to super, you can and usually initialize the instance variables to their initial value and return self at the end of the method. You should always access the instance variables directly from within an initialization method instead of using properties. This is because at the time a property is set, the rest of the object may not yet be completely initialized, creating undefined behavior. Another reason is that properties might trigger Key-Value Coding notifications and cause side effects. Even if you don’t provide custom accessor methods or know of any side effects from within your own class, a future subclass may override the behavior and create them.
Keep in mind that this form of initializer where you return nil on failure of the initializer of the superclass or return selfat the end is the most common type but not the only one. As I said before, you might perform additional checks to see wether the initialization can proceed and return nil at any point for other reasons, or retrieve some other instance of the class and return that one instead of self.

Designated initializers

Sometimes a class provides multiple initializers that take data in different forms. In this case one of the initializers should be chosen as the designated initializer for the class. This initializer has to ensure that all the inherited instance variables are initialized by invoking the designated initializer of the superclass. The designated initializer is typically the one with the most parameters and which does most of the initialization work. The secondary initializers should call this initializer instead of calling the designated initializer of the superclass themselves.
To take our Person class as an example again, we can implement an initializer which takes the first name, the last name and the age as parameters, to make sure that we create objects that are immediately populated correctly:
- (id)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName age:(NSUInteger)age {
    if (!self = [super init])
        return nil;

    _firstName = firstName;
    _lastName = lastName;
    _age = age;
    return self;
}
Le’ts suppose that we then want a convenience initializer that takes the full name as a single string where first name and last name are separated by a space, since it might come in this form from some source, like a web service or database. The designated initializer for the Person class would then be the one we already implemented and this new convenience initializer would call it:
- (id)initWithFullName:(NSString *)fullName age:(NSUInteger)age {
    NSArray *fullNameComponents = [fullName componentsSeparatedByString:@" "];
    return [self initWithFirstName:fullNameComponents[0] 
                          lastName:fullNameComponents[1]
                               age:age];
}