Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Foundation Framework

NSError, Files and JSON

Handle failures with NSError and out-parameters, read and write files with NSFileManager, and parse or generate JSON with NSJSONSerialization in Objective-C, plus exceptions vs errors.

Programs fail: files are missing, networks drop, input is malformed. Objective-C has two failure mechanisms, and Cocoa uses them for different jobs. Exceptions (@try/@catch/@throw) signal programmer errors such as an array index out of range. NSError reports problems that can happen in correct programs, like a missing file, and the caller is expected to handle them. This lesson covers NSError, then the two most common things that produce errors: files and JSON.

The NSError pattern

A method that can fail returns a value (BOOL or an object) and takes an out-parameter NSError **. On success, the return value is meaningful and the error is untouched. On failure, the return is NO or nil and the error is filled in.

OBJECTIVEC
NSError *error = nil;
NSString *text = [NSString stringWithContentsOfFile:@"/tmp/notes.txt"
                                           encoding:NSUTF8StringEncoding
                                              error:&error];
if (text == nil) {
    NSLog(@"Could not read: %@", error.localizedDescription);
    NSLog(@"domain=%@ code=%ld", error.domain, (long)error.code);
    return;
}

Rule: check the return value, not the error variable. A method may set error even when it succeeds. An NSError carries a domain (such as NSCocoaErrorDomain), an integer code, and a userInfo dictionary with NSLocalizedDescriptionKey, an underlying error and more.

Returning your own errors

OBJECTIVEC
NSString * const BankErrorDomain = @"com.example.bank";
typedef NS_ENUM(NSInteger, BankError) { BankErrorInsufficientFunds = 1, BankErrorInvalidAmount };

- (BOOL)withdraw:(double)amount error:(NSError **)error {
    if (amount <= 0) {
        if (error) {
            *error = [NSError errorWithDomain:BankErrorDomain
                                         code:BankErrorInvalidAmount
                                     userInfo:@{ NSLocalizedDescriptionKey: @"Amount must be positive" }];
        }
        return NO;
    }
    if (amount > self.balance) {
        if (error) {
            *error = [NSError errorWithDomain:BankErrorDomain
                                         code:BankErrorInsufficientFunds
                                     userInfo:@{ NSLocalizedDescriptionKey: @"Not enough money" }];
        }
        return NO;
    }
    self.balance -= amount;
    return YES;
}

Always test if (error) before writing through it, because callers may pass NULL if they do not care.

The same pattern in C

The NSError ** convention exists because a function can return only one value. The stand-in below uses a struct pointer as the out-parameter. Notice the NULL check and that the return value decides success.

C Stand-in: out-parameter error reporting

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.

Exceptions are for bugs

OBJECTIVEC
@try {
    id item = array[10];          // raises NSRangeException
} @catch (NSException *e) {
    NSLog(@"%@: %@", e.name, e.reason);
} @finally {
    NSLog(@"always runs");
}

Cocoa conventions say: do not use exceptions for expected failures. Under ARC, an exception that unwinds through code may leak objects, because ARC does not clean up by default. Fix the bug that raises it instead of catching it.

Files with NSFileManager

OBJECTIVEC
NSFileManager *fm = [NSFileManager defaultManager];

NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docs = dirs.firstObject;
NSString *path = [docs stringByAppendingPathComponent:@"notes.txt"];

BOOL exists = [fm fileExistsAtPath:path];

NSError *error = nil;
if (![@"Hello file" writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"write failed: %@", error);
}

NSDictionary *attrs = [fm attributesOfItemAtPath:path error:&error];
NSLog(@"size = %@ bytes", attrs[NSFileSize]);

NSArray *names = [fm contentsOfDirectoryAtPath:docs error:&error];
[fm copyItemAtPath:path toPath:[docs stringByAppendingPathComponent:@"copy.txt"] error:&error];
[fm removeItemAtPath:path error:&error];

Modern code prefers NSURL-based variants (URLForDirectory:..., contentsOfDirectoryAtURL:). Use atomically:YES so a crash mid-write cannot leave half a file. On iOS each app can only touch its own sandbox (Documents, Library, tmp).

For streaming, NSFileHandle reads and writes chunks, and NSInputStream/NSOutputStream provide stream APIs.

A file round trip in C

The same read/write/check cycle with C's FILE API, checking every result as you would an NSError:

C Stand-in: write, read back and delete a file

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.

JSON with NSJSONSerialization

NSJSONSerialization converts between JSON (NSData) and Foundation objects: objects become NSDictionary, arrays NSArray, strings NSString, numbers NSNumber, true/false become @YES/@NO, and null becomes NSNull.

OBJECTIVEC
NSData *json = [@"{\"name\":\"Ada\",\"langs\":[\"ObjC\",\"C\"],\"age\":36}" dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id object = [NSJSONSerialization JSONObjectWithData:json options:0 error:&error];
if (![object isKindOfClass:[NSDictionary class]]) {
    NSLog(@"bad JSON: %@", error);
    return;
}
NSDictionary *dict = object;
NSString *name = dict[@"name"];                        // "Ada"
NSArray *langs = dict[@"langs"];

NSDictionary *payload = @{ @"id": @42, @"tags": @[@"a", @"b"], @"active": @YES };
if ([NSJSONSerialization isValidJSONObject:payload]) {
    NSData *out = [NSJSONSerialization dataWithJSONObject:payload
                                                  options:NSJSONWritingPrettyPrinted
                                                    error:&error];
    NSString *text = [[NSString alloc] initWithData:out encoding:NSUTF8StringEncoding];
}

Always check the type of what you parsed (isKindOfClass:) before using it, since server JSON may not match your expectations, and handle NSNull for null values. Map the dictionary into your model class in one place, a pattern used in the JSON parser project.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After calling a method with an NSError ** argument, what should you check first?

    A method may set the error even on success, so the return value (nil or NO) signals failure.
  2. 2. Why test if (error) before assigning *error?

    Writing through a NULL pointer would crash.
  3. 3. When are exceptions appropriate in Cocoa?

    Exceptions signal bugs; expected failures use NSError.
  4. 4. What does a JSON null become after NSJSONSerialization parses it?

    Collections cannot hold nil, so null is represented by NSNull.

Summary

  • Failing methods return NO/nil and fill an NSError **; check the return value first.
  • Use exceptions only for programmer errors.
  • NSFileManager and writeToFile:atomically:encoding:error: handle files; sandbox rules apply on iOS.
  • NSJSONSerialization maps JSON to Foundation objects; validate types and handle NSNull.

Next: The Objective-C Runtime and Message Sending