Search code examples
iphoneobjective-cxcodensarray

iPhone App - NSArray Issue


Hi I am learning how to code in Objective-C. I want to store the values of the textfields in my view in an array:

NSArray* answers = [NSArray arrayWithObjects:fluidIntake.text, sleepQuality.text, sleepQuantity.text, mentalRecovery.text, 
                          physicalRecovery.text, pretrainingEnergy.text, muscleSoreness.text, generalFatigue.text, nil];

Is this possible? If not is there any cleaner way to store multiple textfield values without having to assign them to an NSString variable..

Update:

Here is the function in my view controller:

-(IBAction)postData:(id)sender{ 
    diary = [[PersonalDiary alloc]init];

    NSArray* answers = [NSArray arrayWithObjects:fluidIntake.text, sleepQuality.text, sleepQuantity.text, mentalRecovery.text, 
                          physicalRecovery.text, pretrainingEnergy.text, muscleSoreness.text, generalFatigue.text, nil];


    [diary post:answers to:  @"http://www.abcdefg.com/test.php"];   
}

It is triggered upon a button press. It should store the 8 values input into the textfields in an NSArray and pass this to a function in my Model class which which at the minute attempts to print the first element in the array (i.e. the first textfield value):

-(void) post:(NSArray*) ans to:(NSString*) link{
    NSLog(@"%@", ans[0]); 
}

But it doesn't, it just prints : PersonalDiary[37114:207] __NSArrayI


Solution

  • You are incorrectly indexing the array in this method and using the wrong kind of string.

    -(void) post:(NSArray*) ans to:(NSString*) link{
        NSString* a = "Hello";
        NSLog(@"%s%d", a, ans[0]); 
    }
    

    ans[0] will print the pointer address of your NSArray and not access your elements. To access your array you need to use objectAtIndex:. All NSString literals need to be prefixed with @. And when you print any kind of Objective-C object use %@ format. Also it is not safe to access objects of the array without checking the count first.

    -(void) post:(NSArray*) ans to:(NSString*) link{
        NSString* a = @"Hello";
        NSLog(@"%@ %@", a, [ans objectAtIndex:0]); 
        //Or print entire array
        NSLog(@"%@", ans);
    }