objective-c

FAQ What's New

Your Trail

xcode > Objective-C

Table of Contents [show]

Copyright Information

1 Introduction

IPhone sdk uses objective-c as the development language. Xcode is the official development environment.

Objective-C was invented by Brad Cox and Tom Love in the early 1980s. The company was called Stepstone. In 1988, Steve Jobs left Apple and formed company NeXT. NeXT licensed objective-c from Stepstone. After the acquisition of NeXT by Apple in 1996, objective-c has since become *the* programming language on Mac.

2 Objective-C and Other Languages

Objective-C is an strict superset of C, meaning any C programs can be compiled by a objective-c compiler. On the other hand, most recent gcc compilers has support for objective-C and should be able to compile objective-C code.

Both being OO extension of C, C++ and objective-c are semantically different:

  1. In c++, you call a method in the form of obj->method(params). In objective-c, however, you send a message to an object in the form of [obj method:params].
  2. C++ supports multiple inheritance, and all methods have to be implemented unless it's virtual. Usually, bindings are decided at compile time, and execution are usually faster. In objective-c, however, messages can be unimplemented, and bindings do not happen until run time. If a message is implemented by an object, it will execute and respond, if not, the program will still compile and run, the message is just ignored.
  3. Unlike C++, Objective-C does not support operator overloading.
  4. Also unlike C++, Objective-C allows an object to directly inherit only from one class (forbidding multiple inheritance). However, categories and protocols may be used as alternative functionality to multiple inheritance.
  5. Compared with C or C++, objective-c code tends to be larger because dynamic typing does not allow methods to be stripped or inlined.
  6. Compared with C++, objective-c has better reflection support. C++ has to rely on external libraries to do that.
  7. Same as C++, Objective-c allows reuse of all existing c libraries.
  8. Objective-c doesn't support namespace, you have to name your classes properly. For example, apple names all it's Mac classes NSxxx, where NS is derived from NextStep.
Compared with other OO languages, objective-c apps are usually smaller because it doesn't require a VM as Java or smalltalk do.

3 Declare a Class

In objective-c, a class is defined in a abc.m file, and it requires an interface implementation named abc.h. For example

@interface classname : superclassname {
    // instance variables
}
+classMethod1;
+(return_type)classMethod2;
+(return_type)classMethod3:(param1_type)parameter_varName;

-(return_type)instanceMethod1:(param1_type)param1_varName :(param2_type)param2_varName; -(return_type)instanceMethod2WithParameter:(param1_type)param1_varName andOtherParameter:(param2_type)param2_varName; @end

[WP]

All regular objective-c classes directly or indirectly inherit from NSObject[AP]. The only exception is NSProxy for remote messaging.

4 Declare Methods

Method declaration format:

[+|-] (return-type) messageName : (type1)name1 {optional-name-ext2:(type2)name2}*;
Where [+|-] denotes class-level or instance-level methods. The default return type is id, the generic data type in objective-c. Objective-c also use this syntax to support ploy-morphism. Think of this as having methods with names messageName, messageNameOptionalNameExt2, messageNameOptionalNameExt2OptionalNameExt3. Therefore you could have
- (int) setOp1:(int)op1 andOp2:(int)op2;
and
- (int) setOp1:(int)op1 andOp3:(int)op3;
These are two different methods, and you could call them separatly by [obj setOp1:value1 (andOp2):value2] and [obj setOp1:value1 (andOp3):value3]. The same message name, the same method signature, but objective-C is able to distinguish between these two. This is not supported in C++ or Java.[OT]

An example abc.m:

@implementation classname 
-(int)method:(int)i
{
    return [self square_root: i];
}

To instantiate a class,

MyObject *o = [[MyObject alloc] init]
init call can be overriden to create your own constructor. Another example from Wikipedia:
-(id) init {
    self = [super init];
    if (self) {
        ivar1 = value1;
        ivar2 = value2;
        .
        .
        .
    }
    return self;
}

Objective-c achieves multiple-inheritance through protocol. For example:

@protocol Locking
- (void)lock;
- (void)unlock;
@end

In your class, you can adopt this protocol by

@interface abc: super-class  
@end;

5 Access Privileges

Default access is protected.

#import <Foundation/NSObject.h>

@interface MyAccessExample: NSObject { @public int publicVar; @private int privateVar; int privateVar2; @protected int protectedVar; } @end

[OT]

6 Dynamic Typing

Objective-c can use dynamic-typing as well as static-typing.

An objective-c class can forward messages to another class.

7 Categories

Class implementation can be broken down into categories. For example, String class can be the base class, while SpellChecker implements the spellchecking functions of Strings, Massager can implement the concatenating functions of Strings, etc. For example

@interface String : Object
@end;

@implementation String @end

@interface String <SpellChecker> @end

@implementation String <SpellChecker> @end

@interface String <Massager> @end

@implementation String <Massager> @end

Then, if you have String *s = [String new]; you should be able to send messages defined in all three classes.

8 Memory Management

In C, you need to alloc memory for your data, and dealloc them when you are done. Objective-C is similar, you have to keep memory management in mind all the time. Objective-C does provide a few things to make your life easier, newer versions even supports garbage collection (not in iphone SDK 3.0). The following keywords are used to manage memory:

  1. alloc, allocate memory
  2. retain, register your interest in an object [objName retain] increases retain count of objName by 1
  3. relase, you aren't interested in that object any more, and aren't against it being decallocated. This decreases ratain count by 1
  4. autorelease, state that you aren't interested in this obj anymore. This obj will be put in a pool and will be released at a later time. Useful if you return an object created locally. Caller can get the obj and immediately retain it if they chooose to, or use it and then let it go without worrying about release.
  5. dealloc, automatically called when retain count of an obj is 0. Never call this unless you are overriding dealloc, when you call [super dealloc] at the end.

Do you need to release an object returned by a method? Convention is, if method name has new, create, copy in it, you need to release it explicitly, otherwise, obj has been autoreleased.

9 Setter, getter, propety, synthesize

You could choose to write your own setters and getters. An alternative is to use property-synthesize. If you declare a local variable property, and then synthesize it, you are implicitly defining standard getters and setters for this variable. When you declare a property, you could choose to make it rw by default, or readonly. You can use your own setter or getter to override implicit getter/setter defined by synthesize.

10 Dot syntax

In objective-c, self.name = @'aaa' and name = @'aaa' can be very different. self.name goes thru setter, while name= doesn't.

11 FAQ

11.1 What's the difference between include and import?

Besides #include directive, objective-c added another directive #import. The only difference is that import won't reload a module if it's already loaded. Meaning, you don't have to use ifndef etc to avoid double-loading of modules.

11.2 Cannot find included file "abc.h"

Check if abc.h exists, and check your include statement for quotes versus brackets (<>). Brackets work for system libraries, however, if your library is one of your own, use quote.

11.3 What is the "id" type?

What is the "id" type? It is sort of like void *. id is a generic C type used by objective-c to refer to any object. For example,

@interface InterfaceExample
@public
- static (id) getSomething: (id) param1;
defines a method called getSomething, which takes in any object, and returns an object.[FAQS]