我想我完全明白了。也许有人可以告诉我出了什么问题。
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"]);
}