01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Creating NSError objects<br />

209<br />

10.2.2 Handling and displaying RentalManagerAPI errors<br />

Let’s look at listing 10.5. What does this code do? First it prepares the ad dictionary<br />

from the values of some text fields. Then it declares a pointer of type NSError and<br />

calls the publishAd:error: method, checking its return value. If it’s YES, a success<br />

message is displayed. If it’s NO (which indicates an error), you check if the error<br />

domain is that of the RentalManagerAPI. If so, you check for different error codes and<br />

construct an appropriate message. Otherwise, you just use the localizedDescription<br />

and finally display it in a UIAlertView. That’s it.<br />

Listing 10.5<br />

Calling the publishAd:error: method<br />

- (IBAction)publishAd:(id)sender {<br />

NSArray *keys = [NSArray arrayWithObjects:@"name", @"city",<br />

@"price", nil];<br />

NSArray *values = [NSArray arrayWithObjects:nameTextField.text,<br />

cityTextField.text,<br />

priceTextField.text, nil];<br />

NSDictionary *ad = [NSDictionary dictionaryWithObjects:values<br />

forKeys:keys];<br />

NSError *error;<br />

if ([RentalManagerAPI publishAd:ad error:&error]) {<br />

UIAlertView *av = [[UIAlertView alloc]<br />

initWithTitle:@"Success"<br />

message:@"Ad published successfully."<br />

delegate:nil<br />

cancelButtonTitle:@"OK"<br />

otherButtonTitles:nil];<br />

[av show];<br />

[av release];<br />

} else {<br />

NSString *message;<br />

Create NSError pointer<br />

if ([error domain] == RMAErrorDomain) {<br />

switch ([error code]) {<br />

case RMAValidationError:<br />

message = [NSString<br />

Create<br />

the “ad”<br />

stringWithFormat:@"%@\nMissing values: %@.",<br />

[error localizedDescription],<br />

[[[error userInfo] objectForKey:<br />

RMAMissingValuesKey]<br />

componentsJoinedByString:@", "]];<br />

break;<br />

case RMAWrongCredentialsError:<br />

break;<br />

default:<br />

message = [error localizedDescription];<br />

break;<br />

}<br />

} else {<br />

message = [error localizedDescription];<br />

}<br />

On success,<br />

display message<br />

Handle errors<br />

differently<br />

Call<br />

RentalManagerAPI<br />

Custom error<br />

domain only<br />

Messages for<br />

validation<br />

errors<br />

Other errors, use<br />

its message

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

Saved successfully!

Ooh no, something went wrong!