01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Creating NSError objects<br />

207<br />

chapters to follow along, by all means do so. Creating a new View-based application<br />

in Xcode should get you on the right track. Otherwise you can always examine the<br />

RentalManagerAPI project in the downloadable source code for this chapter.<br />

Take a look at the code in the following listing.<br />

Listing 10.3<br />

RentalManagerAPI.h<br />

#import <br />

extern NSString * const RMAMissingValuesKey;<br />

extern NSString * const RMAAccountExpirationDateKey;<br />

extern NSString * const RMAErrorDomain;<br />

enum {<br />

RMAValidationError = 1,<br />

RMAAccountExpiredError = 2,<br />

RMAWrongCredentialsError = 3<br />

};<br />

@interface RentalManagerAPI : NSObject {<br />

Required value missing<br />

Account expired<br />

Wrong user/password<br />

}<br />

+ (BOOL)publishAd:(NSDictionary *)anAd<br />

error:(NSError **)anError;<br />

@end<br />

The next listing contains the rest of the code.<br />

Listing 10.4<br />

RentalManagerAPI.m<br />

#import "RentalManagerAPI.h"<br />

Define custom<br />

NSString * const RMAErrorDomain =<br />

error domain<br />

@"com.my-awesome-rental-manager.API";<br />

NSString * const RMAMissingValuesKey = @"RMAMissingValuesKey";<br />

NSString * const RMAAccountExpirationDateKey =<br />

@"RMAAccountExpirationDateKey";<br />

@implementation RentalManagerAPI<br />

+ (BOOL)publishAd:(NSDictionary *)anAd error:(NSError **)anError {<br />

if (anAd == nil) {<br />

@throw [NSException exceptionWithName:@"RMABadAPICall"<br />

}<br />

reason:@"anAd dictionary is nil"<br />

userInfo:nil];<br />

NSMutableArray *missingValues = [NSMutableArray array];<br />

for (NSString *key in [@"name price city"<br />

componentsSeparatedByString:@" "]) {<br />

if ([[anAd objectForKey:key] length] == 0) {<br />

[missingValues addObject:key];<br />

}<br />

Check values<br />

}<br />

missing, if any<br />

if ([missingValues count] > 0) {<br />

If no ad object,<br />

throw an exception

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!