2012-09-29 27 views
1

我想设置一个UITableView来显示文档目录中的数据。从文档目录显示文件在UITableView - iOS5最低

我有点失去了对代码,我试图从谷歌和论坛等许多例子

我没有故事板创建我的应用程序,所以它是所有的代码。

我已经得到了UITableView的显示,所以委托和DataView被设置 - 我只需要内容。

我有这样的代码给你看,但它没有显示任何数据:

- (void)viewDidLoad 
    { 
    [super viewDidLoad]; 

    _firstViewWithOutNavBar = [[UIView alloc] init]; 
    _firstViewWithOutNavBar.frame = CGRectMake(self.view.frame.origin.x, 0, self.v iew.frame.size.width, self.view.frame.size.height); 
    _firstViewWithOutNavBar.backgroundColor = [UIColor whiteColor]; 
    [self.view addSubview:_firstViewWithOutNavBar]; 

    UITableView *tableView = [[UITableView alloc] init]; 
    tableView.frame = CGRectMake(self.view.frame.origin.x, 0,  self.view.frame.size.width, self.view.frame.size.height); 
    tableView.delegate = self; 
    tableView.dataSource = self; 
    [_firstViewWithOutNavBar addSubview:tableView]; 
    } 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
    //alloc and init view with custom init method that accepts NSString* argument 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:indexPath.row]; 
    NSString*pathToPass = [documentsDirectory stringByAppendingPathComponent: 
         [tableView cellForRowAtIndexPath:indexPath].textLabel.text]; //pass this. 

    NSLog(@"%@", pathToPass); 

//_nsarray = [[NSArray alloc] initWithContentsOfFile:pathToPass]; 


    } 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     return [_nsarray count]; 
     NSLog(@"%@", _nsarray); 
    } 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath 
    { 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     } 

     cell.textLabel.text = [NSString stringWithFormat:@"%@",[_nsarray objectAtIndex:indexPath.row]]; 

     return cell; 
     } 

任何帮助将是巨大的。

回答

1

用作numberOfRowsInSectioncellForRowAtIndexPath中表格视图数据源的数组_nsarray永远不会在代码中初始化。你应该做点像

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
_nsarray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:docPath error:NULL]; 

in viewDidLoad

+0

超 - 该代码使其工作非常好谢谢你:-) –

1

你是否在numberOfRowsInSection方法中放置了断点以检查此方法是否已被调用。正如我在你的代码中看到的,你没有初始化你的_nsarray,也没有在该数组中添加任何对象。 所以基本上你的数组包含0个对象,所以不会创建行。 在你的numberOfRowsInSection方法中你已经把nslog放在return语句之后,并且这永远不会被执行,请把它放在return语句之前,这样你才能真正看到数组值。 我希望这会帮助你。

+0

感谢评论帮助:-) –