我想我很懂。也许有人可以告诉我什么是错的。将NSString存储到NSArray
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
- 误差,这是显而易见的。
SOLUTION:
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"]);
}
通常情况下,在这样的地方你的代码是工作,但没有做正确的事的情况下,我找到了解决办法是使其工作**和**做正确的事情太多。 – yuji 2012-04-12 16:38:07
所有我想提到的是,没有语法错误,以便人们专注于逻辑方面。 – DAS 2012-04-12 16:39:33
好的,那么你也许认为你可能很聪明地提及你的代码实际上在做什么而不是正确的事情? – yuji 2012-04-12 16:46:05