Shinonuma
Shinonuma

Reputation: 491

Printing out a concatenated string shows (null)

I want to create a string in the following format: id[]=%@&stringdata[]=%@&id[]=%@&stringdata[]=%@&id[]=%@&stringdata[]=%@& etc. in the for loop i get the id and stringdata, but when I print out the testString is says (null), however when I print out the Ident and Stringdata seperate (the first two NSLogs) the id does get printed out right, stringdata shows also (null) because the strings are empty at that moment so thats normal.

for(NSUInteger i = 0; i<self.childViewControllers.count; i++) {

        NSLog(@"Ident: %@",((myViewController*)[self.childViewControllers objectAtIndex:i]).ident);
        NSLog(@"Stringdata: %@",((myViewController*)[self.childViewControllers objectAtIndex:i]).getQAnswer);

        testString = [testString stringByAppendingString:([NSString stringWithFormat: @"id[]=%@&stringdata[]=%@&",((myViewController*)[self.childViewControllers objectAtIndex:i]).ident ,((myViewController*)[self.childViewControllers objectAtIndex:i]).getQAnswer])];

        NSLog(@"PostString : %@",testString);
}

Upvotes: 1

Views: 97

Answers (3)

fatuous.logic
fatuous.logic

Reputation: 750

NSMutableString *mString = [NSMutableString string];
for(NSUInteger i = 0; i<self.childViewControllers.count; i++)
{
    [mString appendFormat:@"%@id[]=%@",(i>0)?@"&":@"",((myViewController*)[self.childViewControllers objectAtIndex:i]).ident];
    [mString appendFormat:@"&stringdata[]=%@",((myViewController*)[self.childViewControllers objectAtIndex:i]).getQAnswer];
}
NSLog(@"PostString : %@",mString);

hope this helps

using test strings it outputs:

2013-04-04 23:46:54.619 PagingScrollView[93543:c07] PostString : id[]=TESTI&stringdata[]=TESTQ&id[]=TESTI&stringdata[]=TESTQ&id[]=TESTI&stringdata[]=TESTQ&id[]=TESTI&stringdata[]=TESTQ&id[]=TESTI&stringdata[]=TESTQ&id[]=TESTI&stringdata[]=TESTQ&id[]=TESTI&stringdata[]=TESTQ&id[]=TESTI&stringdata[]=TESTQ&id[]=TESTI&stringdata[]=TESTQ&id[]=TESTI&stringdata[]=TESTQ

Upvotes: 0

Marcelo
Marcelo

Reputation: 9944

You're appending that format on testString. As it was not initialized, it's nil and any message to nil returns nil.

You should use:

testString = [NSString stringWithFormat: @"id[]=%@&stringdata[]=%@&",((myViewController*)[self.childViewControllers objectAtIndex:i]).ident ,((myViewController*)[self.childViewControllers objectAtIndex:i]).getQAnswer];

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299565

This means that testString is nil when you go into this loop. So every time you call stringByAppendingString:, you're passing that to a nil object, which does nothing. At the end of the loop, testString is still nil.

Upvotes: 3

Related Questions