DevFly
DevFly

Reputation: 423

How to exit method?

I have a UITextField and I want to check if it is nil to stop executing the method and if it's not to continue. Here is my try, but it doesn't work:

if ([textField.text stringByReplacingOccurrencesOfString:@" " withString:@""] == @"") {
    return;
}

Upvotes: 0

Views: 106

Answers (5)

AppHandwerker
AppHandwerker

Reputation: 1788

Okay so based on your question:

"I have a UITextField and I want to check if it is nil"

then

if (!textField){
// Do whatever here
}

if you want to check if a text field is empty then

if ([textField.text isEqualToString:@""]){
    // Do whatever here
}

If the text field is empty then you shouldn't need to remove spaces from it.

if you need to check that x Number of chracters have been entered then I would use

if ([textField.text length] <= x){
// do whatever here
}

Upvotes: 1

Desdenova
Desdenova

Reputation: 5378

Are you looking for this?

if (![[textField text] length] > 0) {

    return;

}

Upvotes: 0

Dan F
Dan F

Reputation: 17732

If you want to check if its nothing but whitespace, you should use

- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set

and use the character set:

[NSCharacterSet whitespaceCharacterSet];

Then see if the string has a length of 0 at the end

Upvotes: 2

eric.mitchell
eric.mitchell

Reputation: 8845

Maybe this:

if([[textField.text stringByReplacingOccurrencesOfString:@" " withString:@""] length] == 0) {
    return;
}

Upvotes: 1

James Webster
James Webster

Reputation: 32066

Try this:

if ([[textField.text stringByReplacingOccurrencesOfString:@" " withString:@""] isEqualToString:@""]) {
    return;
}

Upvotes: 2

Related Questions