Site icon Treehouse Blog

An introduction to Objective-C

If you are serious about becoming an iOS developer then it is imperative that you learn Objective-C which is an extension of the C language. If you already have experience with an object-oriented language then learning Objective-C should be quite straightforward.

Never written a line of code?

If you’ve never written a line of code and are interested in developing iOS apps then I would highly recommend picking up either of these books: Programming in Objective-C or Cocoa Book

Basic Syntax for a Class

Most object oriented languages have something called a class which encapsulates data and provides access to it. In Objective-C a class can contain instance variables, methods and/or properties. Let us look at an example for a class called Book.

All classes are declared in two parts:
.h – contains the interface which is a declaration of the class structure
.m – contains the implementation of all the methods

The member variables by default are set to private hence you have to write accessor methods which are your getter and setter methods. In the example above, the class Book has getAuthor and setAuthor methods to allow getting and setting the author of a book externally.

Methods

The method signature starts with either a plus or minus, the method name and then followed by arguments.

There are two types of methods in Objective-C: class methods and instance methods.

Book *book = [Book createBookWithTitle:@"A Brave New World"];

A class method is like a static method in Java or C#. It is not tied to an instance of a class and has no knowledge of the instance variables. Class methods should be mainly used for: creating a new object, utility or shared instance for a singleton class. The above method returns an object which is the instance of the class Book.

Instance methods as the name implies are scoped to a particular instance of a class.

    [book title]; // method call without any arguments

Instance methods can also refer to self or super. self refers to its own instance whereas super refers to the parent class.

Properties

When you have too many member variables then having to sit and write getter/setter methods for them can become tedious. Not to mention, the code
looks bloated. That is why Objective-C has has feature called property. The property declaration automatically declares getter/setter methods. Let’s look at a modified version of the Book class with property

@interface Book : NSObject {
    id data;
    int pages;
    NSString *title;
    NSString *author;
}

@property (readonly) NSString *title; // will create only a getter accessor method
@property (retain) NSString *author;  // will create both getter / setter accessor methods

- (void) initWithTitle: (NSString *)aTitle;

+ (id) createBookWithTitle:(NSString *)aTitle;
+ (id) createBookWithTitle:(NSString *)aTitle andAuthor:anAuthor;

@end

The property syntax is very basic starts with @property followed by keywords which allow you define whether you want only a getter method or both a getter and setter methods.

In your implementation you want to synthesize your properties which will actually create the accessor methods.

    @synthesize title, author;

You can always create your own custom getter and setter methods in your implementation.

Implementation

Below is an implementation for the class Book.

#import "Book.h" // import the interface declaration

@implementation Book

@synthesize title, author; // automatically generates the getter & setter methods

- (id) init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

- (id) initWithTitle: (NSString *)aTitle{

    self = [super init];
    if (self) {
        title = [aTitle copy];
    }

    return self;
}

+ (id) createBookWithTitle:(NSString *)aTitle {
    Book *book = [[[self alloc] initWithTitle:aTitle] autorelease];
    return book;
}

+ (id) createBookWithTitle:(NSString *)aTitle andAuthor:(NSString *)anAuthor {
    Book *book = [[[self alloc] initWithTitle:aTitle] autorelease];
    [book setAuthor:anAuthor];
    // OR you can use dot syntax
    // book.author = anAuthor;
    return book;
}

- (void) dealloc
{
    [title release];
    [author release];
    [super dealloc];
}

@end

All the methods in the implementation must be defined between @implmentation and @end

The @synthesize generates the getter and setter methods as needed.

Both the init methods first make a call to the parent class [super init] so that it can initialize and then return an instance. The if statement checks to see if self is a valid instance.

You must be wondering what is id? id allows you to create a loosely or weakly typed variable where the type or class of the variable is determined at runtime. Even though id does not have an asterisk, it denotes a pointer to an object therefore you cannot use it for a scalar type such as int, float, double or char.

For example, this is valid code:

    NSObject *obj = [Book createBookWithTitle:@"A Brave New World"];

This is just wrong

    int i = [Book createBookWithTitle:@"A Brave New World"];

In Objective-C the way to release an object is to use the method release or autorelease. There are a whole set of rules around memory management but to sum it up anytime you create or allocate you own the object and hence must release it. Both the create methods use the method autorelease which basically notifies the system that the object book should be released in the immediate future to release ownership.

If you are interested in learning more do check out the iOS development course.

Convention

The two create methods in the Book class are known as convenience constructors because they combine the two steps of allocating and initializing to return instances of the class. Convention dictates that such methods not start with the word create but with the name of the class. So below is the appropriate way to define those methods:

  + (id) bookWithTitle:(NSString *)aTitle;
  + (id) bookWithTitle:(NSString *)aTitle author:anAuthor;
Exit mobile version