iOS for C# Developer - part 1: Classes and creating objects
In this series I would like to present an overview of differences and similarities in developing iOS and C# apps.
First part is about Object-Oriented features. If you are C# developer and you are starting with Objective-C, Object-Oriented terminology might be confusing.
Interface
In Objective-C, interface is a class declaration (not existing in C#). It is like header file in C++. It has even the same extension: .h
. This is sample interface:
Static (class) methods are distinguished by +
sign. Instance method starts with -
sign. Return types are in brackets. Parameters (brackets and name) are preceded by custom name. In class implementation only parameter name matters.
Implementation
In addition to interface (equivalent of class declaration), Objective-C classes have also implementation files with .m
extension (equivalent of .cpp files in C++). Example implementation for previous interface (class declaration) can look like that:
Protocols
Protocol is equivalent of interface in C#. This is sample protocol definition:
To take advantage of this protocol in some class, it has to be stated in angled brackets, in the interface definition:
Then, its methods have to be implemented in the implementation file:
There are two types of methods in protocol:
- required (default)
- optional
In previous protocol, both methods are required, because it is a default mode. This means, both has to be implemented in the class that use the protocol. In order to make second method optional, keyword @optional
has to be used:
All methods declared after @optional
keyword are optional. In order to declare required method after that, @required
keyword has to be used:
Instantiating objects
Creating instance of object has two steps: allocation and initialization. To create instance of Example
class defined above, message passing syntax is used:
Shortcut for above object creation:
When the class has a constructor with parameters, e.g.:
Initialization looks as follows:
Summary
- Interface - class declaration
- Implementation - class body (implementation of declared methods in class interface)
- Protocol - the same construct as interface in C#
- Object creation:
Example *obj = [[Example alloc] init];