2015-05-09 42 views
0

在我的应用程序的第一个屏幕上,输入一个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

请添加代码 – Azat

+0

只需添加代码。 –

+0

您是否希望pureString在应用的启动之间持续存在? – rdelmar

回答

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