1

我正在测试一种排序算法,并且我有不同的文本文件,其中包含如下值。

2345

6789

4567

我试过这样的事情。

NSString *title = @"test";
NSString *type = @"rtf";

NSMutableArray *test4 = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:title ofType:type]];

但结果是一个(空)数组。

我知道在某些时候我必须将这些值转换为NSNumber对象,但我对 Objective-C 有点迷失。

有人可以给我一些建议吗?

4

2 回答 2

2

您可以使用NSScanner

NSError *error = nil;
NSString *filename = [[NSBundle mainBundle] pathForResource:title ofType:type];
NSString *fileContents = [NSString stringWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:&error];
if (error) NSLog(@"%s: stringWithContentsOfFile error: %@", __FUNCTION__, error);
NSScanner *scanner = [NSScanner scannerWithString:fileContents];

NSMutableArray *array = [NSMutableArray array];
NSInteger i;
while ([scanner scanInt:&i]) {
    [array addObject:@(i)];
}

有关扫描仪、将文件读入字符串和一般字符串编程的讨论,请参阅字符串编程指南

于 2013-07-16T12:34:48.500 回答
0

如果您将扩展名更改为.txt(当然将其保存为纯文本),您可以阅读它们。

当您将数字放在另一个下时,我为这种情况编写了一些代码

1234

2344

2345

这是我正在使用的代码。

NSString *title = @"test";
NSString *type = @"txt";

NSString *file = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:title ofType:type] encoding:NSUTF8StringEncoding error:nil];
NSArray *numberList = [[file stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsSeparatedByString:@"\n"];

NSMutableArray *test4 = [[NSMutableArray alloc] init];
int lastItem = 0; 

for (NSString *listItem in numberList)
{
   //this is added because you most surely have a \n as last item and it will convert to 0
   if(lastItem < listItem.count - 1)
   [test4 addObject:[NSNumber numberWithInt:listItem.integerValue]];
   lastItem++;
}
于 2013-07-16T12:33:10.507 回答