Several years ago, on the 9th January of 2007, Steve Jobs presented the first device, based on iOS platform, – iPhone. Since then our world has become deeply fond of smart devices of Apple corporation and can not be imagined without them: iPhone, iPad, iPod
Programs created for the iPhone are written in Objective-C. Objective-C is often described as a strict superset of the C language. Others call it C with object oriented concepts applied. The first time I saw it, I have to say I felt like I had no idea what I was looking at. It doesn't look like any other programming language that I know. But after you get through your first few programs, you'll find it to be much easier to follow. Being a strict superset of C, if you already have algorithms that are written in C, you should be able to port them over to the iPhone. The following chart shows some expressions that mean close to the same thing in C and Objective-C:
| C/C++ | Objective-C |
#include "library.h" | #import "library.h"" |
this | self |
private: | @private |
protected: | @protected |
public: | @public |
Y = new MyClass(); | Y = [[MyClass alloc] init]; |
try, throw, catch, finally | @try, @throw, @catch, @finally |
Classes
In Objective-C, you declare a class' interface separate from its implementation. You have probably seen a similar separation of interface and implementation in C++ programs where a class' interface is defined in a *.h file the implementation of which is in a *.cpp file. Likewise, in Objective-C, the interface is defined in a *.h file and its implementation in a *.m file.
Every class you create in Objective-C should either directly or indirectly derive from the NSObject base class. The base class doesn't look to do much at first glance, but it contains functionality that the runtime needs for interacting with the object. You don't want to have to implement this functionality yourself.
Methods, Messages, and Object Communication
Most object oriented material you come across will refer to messages being sent among objects. Most of the time, you'll see this implemented through methods. In most cases, the words method and message can be used interchangeably. Objective-C sticks with using the terminology "message". So I'll adhere to that standard within this document.
The syntax for sending a message (which means the same thing as "calling a method") is to enclose the name of the target object and the message to be passed within square brackets. So in C++/C#, you may have send a message using the following syntax:
Class Instantiation and Initialization
An instance of a class is instantiated using the alloc method of the class. alloc will reserve the memory needed for the class. After the memory is allocated, you'll want to initialize it. Every class that has instance members will need to have an init method defined.
No comments:
Post a Comment