TExcelTAD
Home › Objective-C › Classes

Classes

A class is a blueprint for objects. In Objective-C a class is written in two parts:

  • the interface (@interface … @end) declares what the class offers: its superclass, properties and methods;
  • the implementation (@implementation … @end) contains the code.

In a real project they live in two files, Book.h (the header, imported by other files) and Book.m (the implementation). In the playgrounds everything is in one file, interface first.

A first class

objc · try it yourself
#import <Foundation/Foundation.h>

// ---- Book.h ----
@interface Book : NSObject                // Book inherits from NSObject
@property NSString *title;
@property NSInteger pages;
- (void)printSummary;                     // an instance method
- (BOOL)isLong;
@end

// ---- Book.m ----
@implementation Book
- (void)printSummary {
    NSLog(@"\"%@\" has %ld pages", self.title, (long)self.pages);
}

- (BOOL)isLong {
    return self.pages > 400;
}
@end

int main(void) {
    @autoreleasepool {
        Book *novel = [[Book alloc] init];
        novel.title = @"The Long Voyage";
        novel.pages = 512;

        Book *guide = [Book new];         // new = alloc + init
        guide.title = @"Pocket Guide";
        guide.pages = 96;

        [novel printSummary];
        [guide printSummary];
        NSLog(@"novel is long? %@", [novel isLong] ? @"YES" : @"NO");
        NSLog(@"guide is long? %@", [guide isLong] ? @"YES" : @"NO");
    }
    return 0;
}
"The Long Voyage" has 512 pages
"Pocket Guide" has 96 pages
novel is long? YES
guide is long? NO

Things to notice:

  • @interface Book : NSObject means Book is a subclass of NSObject, the root class. Almost every class inherits from it, which gives it alloc, init, description, isEqual: and dozens of other methods.
  • - marks an instance method (sent to an object). A + marks a class method (sent to the class), covered in the Methods lesson.
  • Inside a method, self is the object that received the message.
  • Each object has its own copy of the properties: novel and guide don't share titles.

Instance variables

Properties are backed by instance variables (ivars). For a property named title, the compiler creates an ivar _title. Inside the class you may use the ivar directly, and you can also declare private ivars in braces after @implementation:

objc · try it yourself
#import <Foundation/Foundation.h>

@interface Counter : NSObject
@property NSString *label;
- (void)tap;
- (void)report;
@end

@implementation Counter {
    NSInteger _taps;          // a private instance variable, starts at 0
}

- (void)tap {
    _taps++;
}

- (void)report {
    NSLog(@"%@: %ld taps", _label, (long)_taps);   // _label backs the label property
}
@end

int main(void) {
    @autoreleasepool {
        Counter *likes = [Counter new];
        likes.label = @"Likes";
        [likes tap];
        [likes tap];
        [likes tap];
        [likes report];
    }
    return 0;
}
Likes: 3 taps

All instance variables start out as zero: 0, NO or nil. You never have to worry about uninitialised garbage in an object.

Describing an object

When you print an object with %@, Objective-C sends it the description message. NSObject's version prints the class name and a memory address, which isn't very helpful. Override it to get a readable printout:

objc · try it yourself
#import <Foundation/Foundation.h>

@interface Point3D : NSObject
@property double x;
@property double y;
@property double z;
@end

@implementation Point3D
- (NSString *)description {
    return [NSString stringWithFormat:@"(%.1f, %.1f, %.1f)", self.x, self.y, self.z];
}
@end

int main(void) {
    @autoreleasepool {
        Point3D *p = [Point3D new];
        p.x = 1.5;
        p.z = -2;
        NSLog(@"p = %@", p);
        NSLog(@"as a string: %@", [p description]);
    }
    return 0;
}
p = (1.5, 0.0, -2.0)
as a string: (1.5, 0.0, -2.0)

Naming conventions

Thing Convention Example
Class UpperCamelCase, often with a 2–3 letter prefix TADBook, NSString
Method, property lowerCamelCase printSummary, pageCount
Instance variable underscore + lowerCamelCase _pageCount
Boolean getter reads like a question isLong, hasCover

Objective-C has no namespaces, so Apple recommends a short prefix for your classes (Apple reserves two-letter prefixes such as NS and UI; use three letters for your own code). This course often leaves the prefix out to keep examples short.

Test yourself

Which keyword pair contains a class's method code?

  1. @interface … @end
  2. @implementation … @end
  3. @class … @end
  4. @protocol … @end

What value does a new object's NSInteger instance variable have?

  1. Random garbage
  2. 0
  3. -1
  4. It must be set before use or the program crashes

Which method should you override to control how NSLog(@"%@", obj) prints your object?

  1. print
  2. toString
  3. description
  4. debugName