2013-07-16 47 views
1

我正在测试排序算法,我有不同的文本文件,包含如下值。如何从文本文件创建一个NSNumbers数组?

2345 

6789 

4567 

我已经试过这样的事情。

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

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

但结果是(空)数组。

据我所知,在某些时候我有这些值转换为NSNumber对象,但我与Objective-C的一点点丧失。

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

+0

你NSLog的数组,看看你有什么? –

+0

我得到了(空)阵列 – ragnarok

+0

(请记住,arrayWithContentsOfFile不可能做出RTF文件太大意义,如果RTF意味着富文本格式。arrayWithContentsOfFile仅用于阅读苹果公司的财产清单文件。) –

回答

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)]; 
} 

有关扫描仪的讨论,阅读文件转换成字符串,字符串一般程序,请参见String Programming Guide

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++; 
} 
相关问题