打印出连接的字符串显示(null)

时间:2013-04-04 12:40:30

标签: ios objective-c string

我想以下列格式创建一个字符串:id[]=%@&stringdata[]=%@&id[]=%@&stringdata[]=%@&id[]=%@&stringdata[]=%@&等在for循环中我获取id和stringdata,但是当我打印出testString时会说(null),但是当我打印出来时Ident和Stringdata单独(前两个NSLog)id确实打印出来,stringdata也显示(null)因为那时字符串是空的,所以这是正常的。

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);
}

3 个答案:

答案 0 :(得分:3)

这意味着当您进入此循环时testStringnil。因此,每次调用stringByAppendingString:时,都会将其传递给nil对象,该对象不执行任何操作。在循环结束时,testString仍为nil.

答案 1 :(得分:0)

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);

希望这会有所帮助

使用测试字符串输出:

  

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

答案 2 :(得分:0)

您在testString上添加了该格式。由于未初始化,因此nilnil的任何消息都会返回nil

您应该使用:

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