Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Objects and Classes

Classes and Objects

Learn how to declare a class with @interface, implement it with @implementation, create objects with alloc and init, use instance variables and self, and hide private details.

A class is a blueprint; an object is one thing built from that blueprint. A Person class describes what every person has (a name, an age) and can do (greet, have a birthday), and each Person object holds its own values. Objective-C splits a class definition into two parts, the public @interface and the private @implementation, and creates objects through two messages, alloc and init. This lesson builds a first class from scratch.

The @interface

The interface declares the class name, its superclass, and what outsiders may use. It normally lives in a header:

OBJECTIVEC
// Person.h
#import <Foundation/Foundation.h>

@interface Person : NSObject {
    NSString *_name;
    NSInteger _age;
}

- (void)greet;
- (void)haveBirthday;
- (NSInteger)age;

@end
  • Person : NSObject says Person inherits from NSObject, the root class that provides memory management and basic behaviour. Almost every class derives from it.
  • The braces hold instance variables (ivars). Their names start with an underscore by convention.
  • - (void)greet; declares an instance method. The minus sign means "called on an object". The return type is in parentheses.

The @implementation

The implementation provides the code:

OBJECTIVEC
// Person.m
#import "Person.h"

@implementation Person

- (void)greet {
    NSLog(@"Hi, I'm %@ and I'm %ld.", _name, (long)_age);
}

- (void)haveBirthday {
    _age += 1;
}

- (NSInteger)age {
    return _age;
}

@end

Inside a method, instance variables are used by name, and self refers to the object receiving the message. Properties, covered in the next lessons, generate most of this boilerplate for you.

Creating objects

Objects are created in two steps:

OBJECTIVEC
Person *p = [[Person alloc] init];
  1. +alloc (a class method) reserves memory on the heap and zeroes it, so all instance variables start as 0 or nil.
  2. -init sets the object up and returns it.

Always nest the two calls so the pointer returned by init is the one you keep. The variable p is a pointer; it refers to the object but is not the object. Many classes also offer shorter factory methods such as [NSString stringWithFormat:...] or [NSMutableArray array].

Each object has independent instance variables:

OBJECTIVEC
Person *a = [[Person alloc] init];
Person *b = [[Person alloc] init];
[a haveBirthday];            // only a's age changes

Under ARC the memory is released when the last strong reference disappears. Chapter 5 explains how.

Visibility of instance variables

You can restrict ivar visibility with @private, @protected (the default) and @public:

OBJECTIVEC
@interface Person : NSObject {
    @private
    NSString *_name;
    @protected
    NSInteger _age;
}
@end

Public ivars break encapsulation, so avoid @public.

Hiding details: class extensions and private ivars

The header is the public contract, so keep implementation details out of it. Modern Objective-C declares private ivars directly in the @implementation block, or in a class extension inside the .m file:

OBJECTIVEC
// Person.m
#import "Person.h"

@interface Person () {          // class extension: an unnamed category
    NSString *_name;
    NSInteger _age;
}
- (NSString *)formattedAge;     // private method declaration
@end

@implementation Person {
    NSMutableArray *_nicknames; // another private ivar
}
// ...
@end

Anyone who imports Person.h sees only the public methods.

Introspection

Because the runtime knows each object's class, you can ask about it:

OBJECTIVEC
[p isKindOfClass:[NSObject class]];   // YES (the class or a subclass)
[p isMemberOfClass:[Person class]];   // YES (exactly this class)
[p respondsToSelector:@selector(greet)];  // YES
NSLog(@"%@", NSStringFromClass([p class]));  // Person
NSLog(@"%@", p);                      // <Person: 0x600000f3c0a0>

The default description prints the class name and address. Override description to make logging useful (see the initializers lesson).

Stand-in: a class as a struct and functions

Objective-C classes compile down to something close to C structs plus functions. This stand-in builds a Person the C way: the struct is the instance variables, and each "method" is a function that takes the object as its first (hidden) argument, self.

C Stand-in (C): a class as a struct with functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: private data behind an opaque pointer

A header exposes only declarations, so outsiders cannot touch the fields. In C the equivalent is an incomplete (opaque) type. Here the "header" half comes first and the "implementation" half follows; main can use only the functions.

C Stand-in (C): encapsulation with an opaque type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Forgetting * in the declaration (Person p instead of Person *p).
  • Calling alloc without init, or using the pointer from alloc instead of the one init returns.
  • Putting private ivars and helpers in the public header.
  • Forgetting @end.
  • Importing .m files instead of headers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the - at the start of - (void)greet; mean?

    A minus sign declares an instance method; a plus sign declares a class method.
  2. 2. What are the two steps of creating an object?

    +alloc reserves zeroed memory, -init initializes it.
  3. 3. Where should private instance variables go in modern code?

    Class extensions and @implementation braces keep details out of the header.
  4. 4. What is the difference between isKindOfClass: and isMemberOfClass:?

    isKindOfClass: is true for the class and all its subclasses.

Summary

  • @interface declares the class's public contract; @implementation holds the code.
  • Objects are created with [[Class alloc] init], and each has its own instance variables.
  • Instance methods start with -; inside them self is the receiver.
  • Keep private ivars and helper methods in the .m file with a class extension.
  • Introspection methods such as isKindOfClass: and respondsToSelector: query the runtime.

Next: Methods and Messages