LearnAn introduction to Objective-C

Treehouse
writes on September 27, 2011

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.

Objective-C Class Interface

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.

Objective-C Method Signature

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;

21 Responses to “An introduction to Objective-C”

  1. Anonymous on October 5, 2011 at 12:59 am said:

    http://www.lovetoshopping.org 
    http://www.jerseymall.org
    Cheapest Vans Shoes,Tiffany Jewelry Company,Wholesale Hollister
    Clothing 

  2. What can I say.. The countclock is not accesibil.
    Good Luck.

  3. What can I say.. The countclock is not accesibil.
    Good Luck.

  4. Anonymous on September 27, 2011 at 6:17 am said:

    L28 and L33 with 
    Book *book = [[[self alloc] initWithText:aTitle] autorelease]
    Shouldn’t it be instead:
    Book *book = [[[self alloc] initWithTitle:aTitle] autorelease]

    In any case, thanks for this blog post!

  5. Anonymous on September 27, 2011 at 6:17 am said:

    L28 and L33 with 
    Book *book = [[[self alloc] initWithText:aTitle] autorelease]
    Shouldn’t it be instead:
    Book *book = [[[self alloc] initWithTitle:aTitle] autorelease]

    In any case, thanks for this blog post!

  6. Obj-C Newb on September 27, 2011 at 6:06 am said:

    NSObject obj = [Book createBookWithTitle:@”A Brave New World”];You’re missing the *.

  7. Obj-C Newb on September 27, 2011 at 6:06 am said:

    NSObject obj = [Book createBookWithTitle:@”A Brave New World”];You’re missing the *.

  8. Anonymous on September 27, 2011 at 4:17 am said:

    WRT “If you are serious about becoming an iOS developer then it is imperative that you learn Objective-C”, there are other languages you can code your iOS app in.  For instance, MonoTouch allows using C# and .NET to create your iOS apps. (see http://ios.xamarin.com/).  Similarly, they have MonoDroid for targeting Android (see http://android.xamarin.com/).  You still write your UI to (effectively) the native controls, but for someone with C# (or similar, like Java or Scala, IMHO) experience, this may be faster/simpler/easier than going with Objective-C.

    YMMV, of course, but just wanted to point out an alternative that others may not know about. 🙂

  9. Anonymous on September 27, 2011 at 4:17 am said:

    WRT “If you are serious about becoming an iOS developer then it is imperative that you learn Objective-C”, there are other languages you can code your iOS app in.  For instance, MonoTouch allows using C# and .NET to create your iOS apps. (see http://ios.xamarin.com/).  Similarly, they have MonoDroid for targeting Android (see http://android.xamarin.com/).  You still write your UI to (effectively) the native controls, but for someone with C# (or similar, like Java or Scala, IMHO) experience, this may be faster/simpler/easier than going with Objective-C.

    YMMV, of course, but just wanted to point out an alternative that others may not know about. 🙂

  10. In your example, `createBookWithTitle:` should really just be `bookWithTitle:` (likewise for `createBookWithTitle:andAuthor:`), by standard naming conventions. `autorelease`’d class method initializers are most often named to be the designated initializer, except replacing `init` with the name of the object. Also, `create` in a method name usually implies ownership of the resulting object (i.e. a retain count of 1).

    Also, I think you meant to use `id` where you have NSObject without the `*`.

    Greetings from HN 🙂

    • Thanks for pointing out the code errors. I’ve fixed them. As for `create` I put that there for readability to illustrate that they are creating a new object and not as a naming convention. 

      • Glad to see those fixes.

        Regarding `create`: although it makes the intention perhaps a bit clearer, this is a dangerous anti-convention to introduce to beginners. Method names starting with `create` or `new` have compiler-sensitive semantic properties, which will throw warnings if the retain count of return values from those methods aren’t 1. It’s not pedantry, it’s a syntax error.

  11. In your example, `createBookWithTitle:` should really just be `bookWithTitle:` (likewise for `createBookWithTitle:andAuthor:`), by standard naming conventions. `autorelease`’d class method initializers are most often named to be the designated initializer, except replacing `init` with the name of the object. Also, `create` in a method name usually implies ownership of the resulting object (i.e. a retain count of 1).

    Also, I think you meant to use `id` where you have NSObject without the `*`.

    Greetings from HN 🙂

    • Thanks for pointing out the code errors. I’ve fixed them. As for `create` I put that there for readability to illustrate that they are creating a new object and not as a naming convention. 

      • Glad to see those fixes.

        Regarding `create`: although it makes the intention perhaps a bit clearer, this is a dangerous anti-convention to introduce to beginners. Method names starting with `create` or `new` have compiler-sensitive semantic properties, which will throw warnings if the retain count of return values from those methods aren’t 1. It’s not pedantry, it’s a syntax error.

Leave a Reply

You must be logged in to post a comment.

Want to learn more about iOS?

iOS is the operating system that powers iPhones and iPads. Learn the language, tools and frameworks to build interactive apps on the iOS platform.

Learn more