2017-02-03 23 views
-4

我有一个NSMutableDictionaryusername & password的组合,我如何使用目标C验证它?验证使用NSMutableDictionary

对于防爆:

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; 

[dictionary setObject:@"A" forKey:@"A"]; 
[dictionary setObject:@"B" forKey:@"B"]; 
[dictionary setObject:@"C" forKey:@"C"]; 

我如何可以验证用户名&密码作为键值对。

+2

这里关键是用户名? –

+0

@krishna Skw首先你说过我需要做哪种用户名验证?就像电子邮件验证? –

+0

克里希纳检查我的答案,让我知道您的反馈。 – vaibhav

回答

0

方法很多:

在一个行:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: 
     @"username1", @"pass1", 
     @"username2", @"pass2", 
     @"username3", @"pass3", 
     @"username4", @"pass4", nil]; 

另一种方式:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
[dict setObject:@"username1" forKey:@"pass1"]; 
[dict setObject:@"username2" forKey:@"pass2"]; 
// so on ... 

另一个使用NSArray

NSArray *username = @[@"username1", @"username2", @"username3", @"username4"]; 
NSArray *passwords = @[@"pass1", @"pass2", @"pass3", @"pass4"]; 
NSDictionary *dict = [NSDictionary dictionaryWithObjects:username forKeys:passwords]; 

// see output 
NSLog(@"%@", dict); 
// separately 
NSLog(@"Usernames: %@", [dict allValues]); 
NSLog(@"Passwords: %@", [dict allKeys]); 

可以通过相应地提取单独的键和值,或使用块enumerateKeysAndObjectsUsingBlock验证:

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 

    // place your validation code here 
    NSLog(@"There are %@ %@'s in stock", obj, key); 
}]; 

Complete source

0

要轻松验证字典的内容,您只需访问密钥并验证值。

实施例:

// this assumes that the key is the username and the value is the password 
NSDictionary *credential = @{@"username1":@"pass1",@"username2":@"pass2"/* , ..and so on */}; 

NSString *username = @"<user_input_or_whatever>"; 

NSString *passwordInput = @"<user_input_or_whatever>"; 

NSString *password = credential[username]; 

// if password is nil because username is not present the the condition below fails. 
if([password isEqualToString:passwordInput]){ 
    // both password and username matched 
} 
else{ 
    // username or password didn't matched 
}