我想我很懂。也許有人可以告訴我什麼是錯的。將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