读取Movies.plist文件并显示到table View中
新建一个Movies.plist文件
关键代码:
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDataSource,UITabBarDelegate>
@property(nonatomic,retain) NSDictionary *moveTitles;
@property(nonatomic,retain) NSArray *years;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//path to the property list file
NSString *path = [[NSBundle mainBundle] pathForResource:@"Movies" ofType:@"plist"];
//load the list into the dictionary
self.moveTitles = [[NSDictionary alloc] initWithContentsOfFile:path];
//get all the keys in the dictionary object and sort them
self.years = [[self.moveTitles allKeys] sortedArrayUsingSelector:@selector(compare:)];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.years count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//check the current year based on the section index
NSString *year = [self.years objectAtIndex:section];
//returns the movies in that year as an array
NSArray *moviesSection = [self.moveTitles objectForKey:year];
return [moviesSection count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
}
//get the year
NSString *year = [self.years objectAtIndex:[indexPath section]];
//get the list of movies for that year
NSArray *moviesSection = [self.moveTitles objectForKey:year];
//get the particular movies based on that row
cell.textLabel.text = [moviesSection objectAtIndex:[indexPath row]];
// Configure the cell...
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
//get the year as the section header
NSString *year = [self.years objectAtIndex:section];
return year;
}
@end
运行结果:
原文:http://chaoyuan.sinaapp.com/?p=451