Загрузить данные из .plist в TableView iPhone

Я использую пример из книги «Начало разработки iPhone 4: изучение iOS SDK». В главе 8 показано, как загружать данные из plist в табличное представление. Пример был сделан с помощью Interface Builder. Я хочу сделать это по коду, но сталкиваюсь с проблемами. На экране ничего не отображается....

Вот .ч

#import <UIKit/UIKit.h>
@interface FifthViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
    NSDictionary *names;
    NSArray      *keys;
}
@property (nonatomic, retain) NSDictionary *names;
@property (nonatomic, retain) NSArray *keys;
@end

Вот м

#import "FifthViewController.h"
@implementation FifthViewController
@synthesize names;
@synthesize keys;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

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

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 367) style:UITableViewStyleGrouped];
    [table setDataSource:self];
    [table setDelegate:self];


    NSString *path = [[NSBundle mainBundle] pathForResource:@"sortednames"
                                                 ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc]
                      initWithContentsOfFile:path];
    self.names = dict;
    [dict release];

    NSArray *array = [[names allKeys] sortedArrayUsingSelector:
                  @selector(compare:)];
    self.keys = array;
    [self.view addSubview:table];
    [table release];
}

- (void)dealloc 
{
    [names release];
    [keys release];
    [super dealloc];    
}

- (void)viewDidUnload
{
    self.names = nil;
    self.keys = nil;
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return [keys count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    return [nameSection count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];

    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];

    static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                         SectionsTableIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc]
             initWithStyle:UITableViewCellStyleDefault
             reuseIdentifier:SectionsTableIdentifier] autorelease];
    }

    cell.textLabel.text = [nameSection objectAtIndex:row];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{
    NSString *key = [keys objectAtIndex:section];
    return key;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView 
{
    return keys;
}

@end

person lavitanien    schedule 20.10.2011    source источник


Ответы (1)


Есть несколько проблем с вашим кодом, но основная проблема заключается в том, что вы никогда не добавляете UITableView в качестве представления/подпредставления в свой UIViewController:

UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 367) style:UITableViewStyleGrouped];
[table setDataSource:self];
[table setDelegate:self];
[table release];

// These two lines are what you're missing:
self.view = table;
[table release];

В качестве альтернативы вы можете создать интерфейс в Interface Builder и избежать необходимости создавать этот материал программно.

Кроме того вам не следует создавать свой UITableView там, где вы находитесь. viewDidLoad следует использовать для выполнения любых дополнительных операций после создания всех компонентов интерфейса.

Вы должны перенести создание вашего UITableView в метод loadView:

Дополнительную информацию см. в справочнике по классу UIViewController

person Craig Otis    schedule 20.10.2011