在搜索属性列表时如何检测错误?

时间:2015-05-09 18:02:44

标签: ios objective-c plist

在我的应用的第一个屏幕上,输入一个4位数的代码。当您按“完成”时,它会自动保存代码,应用程序会将视图切换到下一个屏幕。在新屏幕上,它会提取已保存的代码并搜索plist,试图找到与之关联的字符串。除了当用户输入不在plist中的代码时,它目前工作正常。

如何教导它以提供代码的错误提示?plist中不存在?

这是第一个观点:

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];

然后在第二个视图中:

- (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;
}

1 个答案:

答案 0 :(得分:1)

只需检查objectForKey是否返回nil:

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