かなりわかったと思います。多分誰かが私に何が悪いのか教えてくれるでしょう。
NSString:
Patrick\nNice picture!\nAndy\nI like it\nTim\nMe too\n
NSArray
この文字列を次のように格納します。
- NSArray
- NSDictionary
- name (e.g. Andy)
- kommentar (e.g. I like it)
それはどういうわけか論理的なエラーですが、それは私を狂わせます...(コードは機能していますが、正しいことをしていません。)
私のコード:
for (int i = 0; i <= ([[aStr componentsSeparatedByString:@"\n"] count] - 1 / 2); i++) {
NSMutableDictionary * comment = [[NSMutableDictionary alloc] init];
if (i % 2 == 0) {
[comment setValue:[[aStr componentsSeparatedByString:@"\n"] objectAtIndex:i] forKey:@"name"];
[comment setValue:[[aStr componentsSeparatedByString:@"\n"] objectAtIndex:i] forKey:@"kommentar"];
}
[commentsArray addObject:comment];
//NSLog(@"%@", [comment description]);
//NSLog(@"Bla.");
//comment = nil;
}
for (int a = 0; a <= [commentsArray count] - 1; a++) {
NSLog(@"Name: %@ Nachricht: %@", [[commentsArray objectAtIndex:a] valueForKey:@"name"], [[commentsArray objectAtIndex:a] valueForKey:@"kommentar"]);
}
私は得る:
Name: Patrick Nachricht: Patrick
Name: (null) Nachricht: (null)
Name: Andy Nachricht: Andy
Name: (null) Nachricht: (null)
Name: Tim Nachricht: Tim
Name: (null) Nachricht: (null)
Name: Nachricht: //that's because of the last \n
Name: (null) Nachricht: (null)
私も試しました
[comment setValue:[[aStr componentsSeparatedByString:@"\n"] objectAtIndex:i + 1] forKey:@"kommentar"];
...しかし、それは私にout of bounds
-エラーを与えます、それは明らかです。
解決:
for (int i = 0; i <= ([[aStr componentsSeparatedByString:@"\n"] count] - 1); i++) {
NSMutableDictionary * comment = [[NSMutableDictionary alloc] init];
if (i % 2 != 0) {
[comment setValue:[[aStr componentsSeparatedByString:@"\n"] objectAtIndex:i - 1] forKey:@"name"];
[comment setValue:[[aStr componentsSeparatedByString:@"\n"] objectAtIndex:i] forKey:@"kommentar"];
}
[commentsArray addObject:comment];
}
for (int a = 0; a <= [commentsArray count] - 1; a++) {
NSLog(@"Name: %@ Nachricht: %@", [[commentsArray objectAtIndex:a] valueForKey:@"name"], [[commentsArray objectAtIndex:a] valueForKey:@"kommentar"]);
}