2016-04-18 50 views
-1

這是用於更新的TextView文本我的代碼示例中,我想通過所有字符串從JSON響應數組來如何在iOS中的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; 
    } 
} 

}

+1

雅你那麼你在這裏的最後一個值追加到您的TextView的原因,你只能得到最後一個值,在這裏你可以實現兩種方式,一是使用的tableview別人使用的NSMutableString執行循環 –

回答

0

首先你要設置textView文字for loop一次再次代替以前的文本。所以,你必須在append單串並後循環結束所有字符串這個字符串賦值給UITextView.

感謝

0

正常,能只顯示最新的字符串,因爲你正在運行一個循環,最新的對象這個循環將覆蓋前一個

您可以將for循環使用前NSMutableString

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; 

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

希望這將有助於:)

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. 
0
NSArray * arrMsg = [json valueForKeyPath:@"Branches.branch_name"]; 

txt.text = [arrMsg componentsJoinedByString:@"\n"]; //use your saperator which you want to join the strings 
相關問題