Question

On a form, I'm using -[UITextFieldDelegate textFieldDidEndEditing]: to register any errors and store them in a NSMutableArray instance variable formErrors.

I'll use formErrors when my submit button is pressed, or perhaps to disable the button disabled while there are errors on the form.

Error messages get put on formErrors like this:

-(void)textFieldDidEndEditing:(UITextField *)textField 
{
    if ( textField == [self nameField] ) {
        if ( ([[textField text] length] < 2) || ([[textField text] length] > 20) ) {
            [[formErrors addObject:@"Name must contain a minimum of 2 and a maximum of 20 characters only."];
        } else {
            if ([[textField text] rangeOfCharacterFromSet:alphaSet].location != NSNotFound) {
                [[formErrors addObject:@"Name must contain letters and spaces only."];
            }
        }
    }
}

I'm trying to figure out the best way to get the formErrors objects stored so they can be accessed after all fields have been checked.

What has worked for me is to declare an instance var:

{
    NSMutableArray *formErrors;
}

Then initialise in viewDidLoad:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    formErrors = [[NSMutableArray alloc] init];

Then in prepareForSegue: I have some temporary code to check things are working:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    int errCount = [formErrors count];
    // check if all textfield values are filled in if not then disallow form submit
    for (NSString *error in formErrors) {
        NSLog(@"Total %d errors, \n Error Message: %@", errCount, error);
    }

This feels wrong for some reason. Should I be declaring a property instead? All I want to do is, as I enter and leave fields, check if there are any errors; if there are, just store the error message in formErrors, so I can do what I need to do in the prepareForSegue:.

I notice I get slightly confused when dealing with these types of scenarios.

Was it helpful?

Solution

If I were you, I'd stick with simpler & more direct pure ivars -- like you are doing here -- until you have enough experience to form your own opinion.

More generally, I think this is down to preference. Some like to make all their ivars via property declarations. Others prefer the light weight of pure ivar declarations. There are some situations (KVO) where the property declarations will win.

This applies only to crusty old non-ARC, but if you find yourself doing this one or more times:

[myObject release]
myObject = [newObject retain];

You might be better off with property syntax, e.g.

self.myObject = newObject;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top