Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

Practice - Questions and Exercises

Test your Objective-C with commonly asked interview questions on memory, properties, blocks, protocols and the runtime, plus hands-on exercises with solutions and runnable C stand-ins.

You have covered the language, memory management, protocols, blocks, Foundation and the runtime. This last lesson helps you check that it stuck. First, the questions that come up most often in interviews, with short answers. Then exercises with solutions, some of them runnable as C stand-ins. Try to answer each question yourself before reading the answer.

Quick-fire questions

What is the difference between strong and weak? strong owns the object: assignment retains it. weak does not own it and is set to nil automatically when the object is deallocated. Use weak for delegates and parent pointers to avoid retain cycles.

Why is copy used for NSString properties? A caller may pass an NSMutableString and modify it later. copy takes a snapshot; for immutable strings the copy is just a retain.

What is the difference between atomic and nonatomic? atomic guards each getter/setter call with a lock so you never read a half-written value; it does not make compound operations or the whole object thread-safe. nonatomic skips the lock and is faster.

What does ARC do, and what does it not do? It inserts retain/release/autorelease at compile time. It does not break cycles, manage malloced memory, or manage Core Foundation objects without bridging casts.

What is the difference between a category and a class extension? A category adds methods to any class (no stored properties). A class extension (@interface Foo ()) is compiled with the class, may add ivars and properties, and is used for private API.

What happens when you send a message to nil? Nothing; it returns zero (nil, NO, 0). Sending to a deallocated object, on the other hand, crashes.

How is a block different from a function pointer? A block can capture variables from its surrounding scope, is an object, and lives on the stack until copied to the heap.

What does __block do? It makes a captured local variable shared and mutable, instead of a read-only copy.

How do you avoid a retain cycle in a block? Capture self weakly (__weak typeof(self) weakSelf = self;), and promote it to strong inside the block while it runs.

What is the difference between isKindOfClass: and isMemberOfClass:? Kind: the class or a subclass. Member: exactly that class.

Explain method swizzling. Exchanging the implementations of two selectors at runtime with method_exchangeImplementations. Powerful, global and fragile.

What is KVO, and what is the classic bug? Observers are notified when a property changes. The classic bugs are forgetting to remove the observer (a crash on dealloc) and observing without a unique context.

NSArray vs NSMutableArray? The first never changes after creation and is safe to share; the second can be modified. Store arrays in copy properties.

+load vs +initialize? +load is called once when the class is loaded, before main, for every class and category. +initialize is called lazily before the first message to the class (and can run for subclasses too). Keep both light.

What is instancetype? A return type meaning "an instance of the receiving class", so subclasses get the right type from init and factory methods.

What is a designated initializer? The initializer that every other initializer in the class ultimately calls, and that itself calls the superclass's designated initializer.

Exercise 1: Predict the counts

Given this code under manual counting, what is the retain count at each marked line?

OBJECTIVEC
NSObject *a = [[NSObject alloc] init];   // (1)
NSMutableArray *list = [NSMutableArray array];
[list addObject:a];                      // (2)
[list addObject:a];                      // (3)
[a release];                             // (4)
[list removeObjectAtIndex:0];            // (5)

Work it out before reading on. The answers: (1) 1, (2) 2, (3) 3 (an array retains each addition, even duplicates), (4) 2, (5) 1. The object dies when the array is removed or deallocated.

Verify with a model of the same sequence:

C Stand-in: trace the retain counts

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.

Exercise 2: Find the bugs

OBJECTIVEC
@interface Timer : NSObject
@property (nonatomic, strong) id<TimerDelegate> delegate;   // bug A
@property (nonatomic, strong) NSString *label;              // bug B
@property (nonatomic, strong) void (^onFire)(void);         // bug C
@end

@implementation Page
- (void)setup {
    self.timer.onFire = ^{ [self refresh]; };               // bug D
    NSMutableArray *rows = [NSMutableArray array];
    [rows addObject:nil];                                   // bug E
    if (self.title == @"Home") { ... }                      // bug F
}
@end

Solutions:

  • A: delegate should be weak (cycle with its owner).
  • B: copy so a mutable string cannot change underneath.
  • C: block properties use copy.
  • D: self owns the timer which owns the block which owns self: use weakSelf.
  • E: collections cannot hold nil: it throws. Use [NSNull null].
  • F: == compares pointers; use isEqualToString:.

Exercise 3: Implement a stack with a category

Write a category NSMutableArray (Stack) with push:, pop (returning nil when empty) and peek.

OBJECTIVEC
@interface NSMutableArray (Stack)
- (void)push:(id)object;
- (nullable id)pop;
- (nullable id)peek;
@end

@implementation NSMutableArray (Stack)
- (void)push:(id)object { [self addObject:object]; }
- (id)peek { return self.lastObject; }
- (id)pop {
    id top = self.lastObject;
    if (top) [self removeLastObject];
    return top;
}
@end

Notice that pop retains the object (the id top local is strong) before removing it, so it survives the removal. In manual counting you would have to retain and autorelease it yourself. Here is the same behavior as a C stand-in, with a stack that returns "nil" for an empty pop:

C Stand-in: a stack that pops nil when empty

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.

Exercise 4: Predict the output

OBJECTIVEC
int x = 1;
void (^b)(void) = ^{ NSLog(@"x = %d", x); };
x = 2;
b();

__block int y = 1;
void (^c)(void) = ^{ y += 10; };
c();
NSLog(@"y = %d", y);

Prints x = 1 (captured by value at creation) and y = 11 (__block shares the variable). The stand-in confirms the idea with a plain value copy versus a pointer:

C Stand-in: capture by value vs shared variable

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.

Exercise 5: Design questions

Without code, decide and justify:

  1. You store a list of favorite colors in a model and expose it to the view. Which attribute, and should you expose the mutable version? (copy for an NSArray, and expose only the immutable type; offer methods to add and remove.)
  2. A network class calls you back when done. Delegate, block or notification? (One caller wanting one result: a block. A stream of events with several decisions: a delegate. Many unrelated listeners: a notification.)
  3. You must run a 2-second parse without freezing the UI. (A background queue with GCD, then dispatch the result to the main queue.)
  4. Two screens need to know the user changed the theme. (A notification or KVO on a settings object, not direct references.)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A category on NSString defines trim, and the next OS release adds a private trim. What is the safe practice?

    Prefixed names cannot collide with future framework methods.
  2. 2. What is printed by NSLog(@"%d", (int)[nil count])?

    A message to nil returns zero for integer return types.
  3. 3. Which is a correct reason to use +load?

    +load runs at launch for every class, so it must be fast; swizzling is the typical use.
  4. 4. A view controller registers a block with NSNotificationCenter that uses self, and never removes it. What can go wrong?

    The center holds the block, the block holds self; remove the token in dealloc or capture self weakly.

Summary

  • Know the property attributes (strong, weak, copy, assign, atomic) and when each applies.
  • Know the rules of ownership, cycles, blocks, categories versus extensions, and message sending to nil.
  • Practice tracing retain counts and capture semantics by hand until it is automatic.
  • Build the projects again from memory, then extend them. That is the best way to make Objective-C stick.

Back to the track: Objective-C tutorial