Search code examples
iosobjective-cplist

How can I detect an error when searching through a property list?


On the first screen of my app, you enter a 4 digit code. When you press "Done", it saves the code automatically and the app switches views to the next screen. On the new screen, it pulls up the saved code and searches through a plist trying to find the string it's associated with. It currently works perfectly except for when the user enters a code that is not in the plist.

How can I teach it to give an error alert of the code is not present in the plist?

This is the first view:

NSString *pureString = [[detectionString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:pureString forKey:@"beaverID"];
[defaults synchronize];

ViewController *Flip = [[ViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:Flip animated:YES];

Then in the second view:

- (void)viewDidLoad {
    //Loading the unique student's ID code:
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *loadstring = [defaults objectForKey:@"beaverID"];

    //Loading the user's first name from the first .plist:
    NSString *error2 = nil;
    NSPropertyListFormat format2;
    NSString *plistPath2;
    NSString *rootPath2 = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];

    NSString *file2 = @"User Data.plist";
    plistPath2 = [rootPath2 stringByAppendingPathComponent:file2];

    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath2]) {
        plistPath2 = [[NSBundle mainBundle] pathForResource:@"User Data" ofType:@"plist"];
    }

    NSData *plistData2 = [[NSFileManager defaultManager] contentsAtPath:plistPath2];
    NSDictionary *tempDict2 = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistData2 mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format2 errorDescription:&error2];

    NSString *person = [@"BCDS" stringByAppendingString:loadstring];
    NSString *string = [tempDict2 objectForKey:person];
    NSString *message = [@"Hello, " stringByAppendingString:string];
    welcome.text = message;
}

Solution

  • Just check if objectForKey returns nil:

    NSString *string = [tempDict2 objectForKey:person];
    if (string == nil)
        [[[UIAlertView alloc] 
            initWithTitle:@"Error" message:@"Cannot find item" 
            delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];