我有一个对象的文本文件,我正在从中提取信息,数据存储如下:
name。| description | 2013-10-19 23:25:58 +0000 | NO | NO
name。| description | 2013-10-19 23:25:58 +0000 | NO | NO
name。| description | 2013-10-19 23:25:58 +0000 | NO | NO
要将每一行放入一个字符串数组中,我会执行以下操作:
NSArray *objectArray = [saveData componentsSeparatedByString:@"\n"];
将生成一个包含各个字符串的数组:
name。| description | 2013-10-19 23:25:58 +0000 | NO | NO
然后我想要额外添加每个字符串的每个字段。
NSMutableArray *items = [[NSMutableArray alloc] init];
for (NSString *string in objectArray) {
[items removeAllObjects];
[items addObject:[string componentsSeparatedByString:@"|"]];
for (int i = 0; i < [items count]; i++) {
NSLog(@"%d %@", i, [items objectAtIndex:i]);
}
}
但这只是产生整条线而不是单个字段?
编辑:我的问题是我的原始saveData字符串。让我没先验证它是正确的!
上面的代码工作正常,并产生如下输出:
2013-10-20 11:15:11.152 Wakely[3571:11603] 0 (
"name.1",
"desc",
"2013-10-20 00:15:05 +0000",
NO,
NO
)
2013-10-20 11:15:11.155 Wakely[3571:11603] 0 (
"name.2",
"desc",
"2013-10-20 00:15:07 +0000",
NO,
NO
)
我不应该使用[items objectAtIndex:0]来获取name1吗?它似乎已被存储为一个整体,单个对象与行描述而不是5个分隔的字符串?
答案 0 :(得分:4)
NSString* test = @"name.|description|2013-10-19 23:25:58 +0000|NO|NO";
NSArray* testarray = @[test,test,test];
NSMutableArray* finalArray = [[NSMutableArray alloc]init];
for (NSString* teststring in testarray) {
[finalArray addObject:[teststring componentsSeparatedByString:@"|"]];
}
NSLog(@"%@",finalArray);
结果:
2013-10-20 01:46:47.484 test[38523:60b] (
(
"name.",
description,
"2013-10-19 23:25:58 +0000",
NO,
NO
),
(
"name.",
description,
"2013-10-19 23:25:58 +0000",
NO,
NO
),
(
"name.",
description,
"2013-10-19 23:25:58 +0000",
NO,
NO
)
)
用你的东西编辑:
NSArray *objectArray = [saveData componentsSeparatedByString:@"\n"];
NSMutableArray* finalArray = [[NSMutableArray alloc]init];
for (NSString* teststring in objectArray) {
[finalArray addObject:[teststring componentsSeparatedByString:@"|"]];
}
NSLog(@"%@",finalArray);
编辑2:
NSArray* firstItem = finalArray[0];
NSString* name1 = firstItem[0];
答案 1 :(得分:0)
与incmiko的做法类似,但使用块而不是for循环。
NSString* test = @"name.|description|2013-10-19 23:25:58 +0000|NO|NO";
NSArray *multipleLines = @[test, test, test];
[multipleLines enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%@", [obj componentsSeparatedByString:@"|"]);
}];
输出:
2013-10-19 19:48:58.522 Strings[407:303] (
"name.",
description,
"2013-10-19 23:25:58 +0000",
NO,
NO
)
2013-10-19 19:48:58.523 Strings[407:303] (
"name.",
description,
"2013-10-19 23:25:58 +0000",
NO,
NO
)
2013-10-19 19:48:58.524 Strings[407:303] (
"name.",
description,
"2013-10-19 23:25:58 +0000",
NO,
NO
)
答案 2 :(得分:0)
这是因为您在items数组中添加了NSArray作为整个对象。尝试使用代码,它应该打印单个项目,而不是整个数组:
NSString* test = @"name.|description|2013-10-19 23:25:58 +0000|NO|NO";
NSString* test1 = @"name1.|description1|2013-10-19 23:25:58 +0001|NO1|NO1";
NSArray *objectArray = @[test,test1];
NSMutableArray *items = [NSMutableArray array];
for (NSString *string in objectArray) {
[items addObjectsFromArray:[string componentsSeparatedByString:@"|"]];
}
NSLog(@"First Item = %@", items[0]);