在iOS中使用Plist文档目录填充TableView

时间:2014-04-19 03:47:50

标签: ios objective-c uitableview plist

  • 我是Objective-C的新手,所以非常感谢任何帮助。
  • 我有TableView成功从我的Xcode项目中的Data.plist文件中撤回列表,但我需要从文档目录中提取。
  • 我看过很多关于此的帖子,但似乎无法让它为我工作。
  • 下面是我的.m文件。就像我说的,它会拉回数据,但我需要根据我的Documents plist副本动态更改它。

提前致谢!

 @synthesize content = _content;

 - (NSArray *)content
{
    if (!_content) {
        _content = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]];
    }
    return _content;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.content count];
}

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

    // Configure the cell...
    cell.textLabel.text = [[self.content objectAtIndex:indexPath.row] valueForKey:@"Name"];
    cell.detailTextLabel.text = [[self.content objectAtIndex:indexPath.row] valueForKey:@"Score"];

    return cell;
}

1 个答案:

答案 0 :(得分:1)

试试这个:

第1步:在.h文件中声明一个全局变量

@property (nonatomic,retain) NSMutableDictionary *contents;

第2步:在.m文件中设置合成

@synthesize contents;

第3步:将plist文件从 mainbudle移动到文档目录

-(void) createPlistDocuments
{
    // Get path to documents directory
    NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    // Finds the contained Documents directory
    NSString *documentsDirectory = [arrayPaths objectAtIndex:0];
    NSError *error;
    // Create an object that we will later use to look for a file and return a boolean value on whether or not it exists
    NSFileManager *manager = [NSFileManager defaultManager];
    // File we want to move, stored in original top level directory
    NSString *demoFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
    // Define where we want it moved to and name it
    NSString *demoFileMoved = [NSString stringWithFormat:@"%@/data.plist", documentsDirectory];
    // Attempt the copy
    if ([manager copyItemAtPath:demoFile toPath:demoFileMoved error:&error] != YES)
    NSLog(@"Unable to move file: %@", [error localizedDescription]);
}

第4步:文档目录中读取plist数据

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self createPlistDocuments];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];
    NSString *path = [NSString stringWithFormat:@"%@/data.plist",documentsDirectoryPath];
    contents = [NSArray arrayWithContentsOfFile:path];
    NSLog(@"%d", contents.count);

}

有关简要说明,请参阅此示例... TechDevMobile(IOS-Message-Chat)