-1

I have an array of text fields. I'm using a for loop to go through the array and check to see if the text field's text attribute is empty.

NSArray *arrayOfTextFields = [NSArray arrayWithObjects: _nameTextfield, _emailTextfield, _phoneTextfield, _termTextfield, _schoolTextfield, _graduationTextfield, _gpaTextfield, _degreeTextfield, _interestTextfield, _groupTextfield, _appliedTextfield, nil];

for (int i = 0; i < [arrayOfLabels count]; i++) {

    if ([[arrayOfTextFields objectAtIndex:i] isEqualToString:@""]) {
        NSLog(@"if statement ran");
    }
}

Obviously the if statement does not run because it is comparing a text field to a string. I can't figure out how to do this syntactically in Objective-C. Something like this would be incredibly easy in C++ or Java, it might look something like arrayOfTextFields[i].text == ""; That is essentially what I'm trying to do. I have struggled to find references to the sort of thing online.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • If you're just starting out, asking questions on Stack Overflow is not the place you need to be. You should find a good book or a series of online tutorials. Have a look at [Good resources for learning ObjC](http://stackoverflow.com/q/1374660). The Big Nerd Ranch books are excellent, and lots of people like the Stanford iOS course on iTunes U. Good luck! – jscs Jul 22 '15 at 22:56
  • Thank you for the reference, however, right now I do not have the time to scour a bunch of tutorials to look for an answer that may not be there. Even if you don't tell me how to do it, I would love some hints and pointers in the right direction. – Alex Cauthen Jul 22 '15 at 23:02

2 Answers2

0
NSArray *arrayOfTextFields = [NSArray array];//set your labels here

    for (UITextField *textField in arrayOfTextFields) {

        if ([textField.text isEqualToString:@""]) {
            NSLog(@"if statement ran");
        }
    }

or you can try this also..

NSArray *arrayOfTextFields = [NSArray array];//set your labels here

    for (int i = 0; i < [arrayOfTextFields count]; i++) {

        if ([((UITextField*)[arrayOfTextFields objectAtIndex:i]).text isEqualToString:@""]) {
            NSLog(@"if statement ran");
        }
    }
0

The strings in the text fields are not the same as the text fields themselves. You must access the text property of the field in order to compare it to another string. The syntax is exactly the same as what you quoted for C++ or Java: arrayOfTextFields[i].text.

You can also use [[arrayOfTextFields objectAtIndex:i] text]. The two are completely equivalent in effect (there are some differences in implementation that aren't important here).

You should also typically use fast enumeration with NSArrays. Thus your loop can look like this:

for( UITextField * field in array ){
    if( [field.text isEqualToString:@""] ){
        // Do stuff
    }
}
jscs
  • 63,694
  • 13
  • 151
  • 195