使用NSMutableDictionary验证

时间:2017-02-03 09:43:57

标签: ios objective-c xcode nsmutablearray

我有一个NSMutableDictionaryusername & password的组合,我如何使用目标C对其进行验证?

对于Ex:

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
}