SimplyKiwi
SimplyKiwi

Reputation: 12444

Textfield text match array from text file

This is my code to get each word from a text file into a NSArray but it simply doesn't work when I try to match one of the words in the array to my textfield.

-(NSString*) replaceBadWords:(NSString*)userText {

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"badwords" ofType:@"txt"];
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSArray *lines = [fileContents componentsSeparatedByString:@"\n"];
NSLog(@"lines: %@", lines);

for(NSString* s in lines){
    userText =[userText stringByReplacingOccurrencesOfString:s withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[userText length])];
}

return userText;
}

- (void)textFieldDidChange:(NSNotification *)notif {
    NSLog(@"textfielddidchange");
    NSString *tmp = [self replaceBadWords:Name.text];
    NSLog(@"tmp: %@", tmp);
    if(![tmp isEqualToString:Name.text])
        Name.text = tmp;
}

This code fires when the textfield text changes whenever the user types a new word/letter. Any ideas why this wouldn't work?

In the end, I just want to see if the textfield text matches a word that was in the text file, and if it is, then make the textfield.text, nil. But this code does not do that, I just need to fix that.

Upvotes: 1

Views: 182

Answers (2)

Daniel
Daniel

Reputation: 577

Use this: link.

I think you need :

- (void)textFieldDidBeginEditing:(UITextField *)textField

because:

- (void)textFieldDidChange

fires over and over after first first letter written.

Upvotes: 1

Daniel
Daniel

Reputation: 577

This

if(![tmp isEqualToString:Name.text])

means that they should not be the same. Is that what u want?

Upvotes: 1

Related Questions