2012-04-23 55 views
1

我有一个应用程序,允许用户保存和打开文本文件。保存和打开文件相当直接简单,但我必须让用户轻松选择要打开的文件。我决定用UITableView来做到这一点。显示UITableView中的文件NSArray - iOS 5

当TableView加载到我的视图控制器中时,我的目标是使用Documents文件夹(iOS App Sandbox的一部分)中所有用户文本文件的名称填充TableView。

我对如何做一个总体思路:

  1. 获取文档文件夹中的内容并把它放在一个阵列

    NSString *pathString = [[NSBundle mainBundle] pathForResource:@"Documents" ofType:@"txt"]; 
    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathString error:nil]; 
    NSLog(@"Contents of directory: %@", fileList); 
    

    但这总是返回:(null)在输出窗口。 我的应用程序的文档文件夹的路径是什么?

  2. 放入的UITableView

    阵列我想我会用numberOfRowsInSection方法来做到这一点。 这是执行此类操作的正确位置吗?我应该使用不同的方法吗?

  3. 最后,应用程序将获得所选单元格的值并使用该值打开文件。


我的主要问题在这里:我怎么能放置物品(目录的特别内容)到一个NSArray,然后显示一个UITableView数组?

任何帮助非常感谢!

+0

'[一个NSBundle mainBundle] pathForResource:@ “文档” ofType:@ “TXT”];'实际上将让你应用程序包中的* single *资源“Documents.txt”。看看文档。 – 2012-04-23 22:10:52

+0

另外,你应该使用' - (NSArray *)pathsForResourcesOfType:(NSString *)扩展inDirectory:(NSString *)subpath'来代替。否则,你主要得到它 – 2012-04-23 22:17:44

回答

3

您可以用获取路径:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

可以使用取得相应目录的内容:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil]; 

至于在一个UITableView显示一个NSArray,你应该检查Apple的文档UITableView数据源协议:

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html

您使用的cellForRowAtIndexPath方法以实际填充表,像这样的工作:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; 

    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyIdentifier"] autorelease]; 
    } 

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    cell.textLabel.text = [fileList objectAtIndex:indexPath.row] 

    return cell; 
} 
+0

谢谢!但是,如何获取目录的内容,而不是目录的路径?那可能吗? – 2012-04-24 23:09:39

+0

我将此添加到我原来的答案中 – 2012-04-25 21:05:13