Advertisement
CGC_Codes

Objective-C Error Handling

Jan 30th, 2017
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
  2. NSString *desc = NSLocalizedString(@"Unable to complete the process", @"");
  3. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
  4. NSError *error = [NSError errorWithDomain:domain code:-101 userInfo:userInfo];
  5.  
  6. #import <Foundation/Foundation.h>
  7.  
  8. @interface SampleClass:NSObject
  9.  
  10. -(NSString *) getEmployeeNameForID:(int) id withError:(NSError **)errorPtr;
  11.  
  12. @end
  13.  
  14. @implementation SampleClass
  15.  
  16. -(NSString *) getEmployeeNameForID:(int) id withError:(NSError **)errorPtr{
  17.     if(id == 1)
  18.     {
  19.        return @"Employee Test Name";
  20.     }
  21.     else
  22.     {
  23.        NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
  24.        NSString *desc =@"Unable to complete the process";
  25.        NSDictionary *userInfo = [[NSDictionary alloc]
  26.        initWithObjectsAndKeys:desc,
  27.        @"NSLocalizedDescriptionKey",NULL];  
  28.        *errorPtr = [NSError errorWithDomain:domain code:-101
  29.        userInfo:userInfo];
  30.        return @"";
  31.     }
  32. }
  33.  
  34. @end
  35.  
  36.  
  37. int main()
  38. {
  39.    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  40.    SampleClass *sampleClass = [[SampleClass alloc]init];
  41.    NSError *error = nil;
  42.    NSString *name1 = [sampleClass getEmployeeNameForID:1 withError:&error];
  43.  
  44.    if(error)
  45.    {
  46.       NSLog(@"Error finding Name1: %@",error);
  47.    }
  48.    else
  49.    {
  50.       NSLog(@"Name1: %@",name1);
  51.    }
  52.  
  53.    error = nil;
  54.  
  55.    NSString *name2 = [sampleClass getEmployeeNameForID:2 withError:&error];
  56.  
  57.    if(error)
  58.    {
  59.       NSLog(@"Error finding Name2: %@",error);
  60.    }
  61.    else
  62.    {
  63.       NSLog(@"Name2: %@",name2);
  64.    }
  65.  
  66.    [pool drain];
  67.    return 0;
  68.    
  69. }
  70.  
  71. 2013-09-14 18:01:00.809 demo[27632] Name1: Employee Test Name
  72. 2013-09-14 18:01:00.809 demo[27632] Error finding Name2: Unable to complete the proces
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement