Загрузить данные из .plist в TableView iPhone - PullRequest
0 голосов
/ 20 октября 2011

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

Вот это .h

#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

1 Ответ

1 голос
/ 20 октября 2011

Есть несколько проблем с вашим кодом, но основная проблема в том, что вы никогда не добавляете 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];

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

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

Вам следует переместить создание UITableView в метод loadView:

Обратитесь к справке по классу UIViewController для получения более подробной информации

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...