这是我用于更新textview文本的代码示例,我想传递来自JSON响应的数组中的所有字符串
- (void)viewDidLoad {
[super viewDidLoad];
NSString *parseURL = @"url link";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
NSArray *messageArray = [json objectForKey:@"Branches"];
for (NSDictionary * dataDict in messageArray) {
NSString *me = [dataDict objectForKey:@"branch_name"];
txt.text = me;
}
}
}
答案 0 :(得分:0)
首先,您要一次又一次地在textView
中设置for loop
文字,以替换之前的文字。因此,您必须append
单个字符串中的所有字符串,并在for循环结束后将此字符串分配给UITextView.
由于
答案 1 :(得分:0)
正常情况下,它会显示最新的字符串,因为您正在运行循环,此循环中的最新对象会覆盖前一个
您可以在NSMutableString
循环
for
NSMutableString *branchesString = [[NSMutableString alloc] init];
然后进入你的for循环呢
[branchesString appendString:[NSString stringWithFormat:@"%@, ", [dataDict objectForKey:@"branch_name"]]];
循环后,您可以将此字符串设置为textView.text
您的代码看起来像这样
if(data){
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
NSArray *messageArray = [json objectForKey:@"Branches"];
NSMutableString *branchesString = [[NSMutableString alloc] init];
for (NSDictionary * dataDict in messageArray) {
[branchesString appendString:[NSString stringWithFormat:@"%@ ", [dataDict objectForKey:@"branch_name"]]];
}
txt.text = branchesString;
}
答案 2 :(得分:0)
只需改变你的for循环,
for (NSDictionary * dataDict in messageArray) {
NSString *me = [dataDict objectForKey:@"branch_name"];
txt.text = [txt.text stringByAppendingString:me]; //change
//txt.text =messageArray;
// Do any additional setup after loading the view, typically from a nib.
}
如果你想要新行中的下一个字符串,那么
txt.text = [txt.text stringByAppendingString:[NSString stringWithFormat:@"%@\n",txt.text]];
如果想用逗号分隔,那么
txt.text = [txt.text stringByAppendingString:[NSString stringWithFormat:@"%@,",txt.text]];
希望这会有所帮助:)
答案 3 :(得分:0)
for
/ for-each
循环是多余的。在阵列上使用componentsJoinedByString:
。
NSArray *messageArray = [json objectForKey:@"Branches"];
txt.text = [messageArray componentsJoinedByString:@"\n"]; // linebreak between each message
// Use a space, comma, linebreak (\n), or whatever separator you prefer.
答案 4 :(得分:0)
NSArray * arrMsg = [json valueForKeyPath:@"Branches.branch_name"];
txt.text = [arrMsg componentsJoinedByString:@"\n"]; //use your saperator which you want to join the strings