Search string in an array and then display in textview in iphone
I have the array which stores the username and password. My array structure will be as follows
Array: (
{
password = 123;
开发者_StackOverflow中文版username = sam;
},
{
password = 123456;
username = 123;
},
{
password = david123;
username = David;
}
)
When i click the login button i wanted to check whether the text in my username textbox is equal to the username in the array. Can any one help me in this issue
Thanks in advance
I strongly recommend that you consider a different design. Storing passwords in clear text has been out of fashion for at least three decades now: it's very easy for someone to recover a user's iPhone or their iTunes backup of their iPhone and read all of the passwords. It's also easy for one user to read everyone else's password.
Depending on how you need to use the password, consider one of these options:
- if the password must be known to the app (e.g. to authenticate against a web service), store credentials in the Keychain. Use the 'account' attribute of each keychain item to store the username. Your search for a valid username then becomes simply a keychain search for an item with the matching value in the account attribute.
if you don't need to know the password (e.g. you're just doing local access control on the phone), then hash the password and store the hash. Instead of the array you proposed in your question, use a dictionary:
{ "sam": "HASH(salt1+password)", "david": "HASH(salt2+letmein)", ... "otheruser": "HASH(saltN+supersecret)" };
so you don't need a complicated loop-through-array as proposed elsewhere, you just look up [dict objectForKey: userName]
and if you get nil
, you didn't have a valid username.
If your username and password is stored as an object in the array something like this would work.
BOOL correctUsername = NO;
for (int i =0; i < usernameArray.count; i++) {
CustomObject *tempObj = [usernameArray objectAtIndex:i];
if (tempObj.userName == textFld.text) {
correctUsername = YES;
}
}
If your username and password were stored separately in the array then you would have to jump by 2 instead of one on the for loop to get just the username. Not the best way. The best way would be the object way.
Use NSPredicate
.
NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:@"username LIKE [cd] %@", textField.text];
NSArray *result = [array filteredArrayUsingPredicate:predicate];
if ([result count] > 1) {
// User Exists
}
精彩评论