Проблема с отображением данных NSMutableArray в табличном представлении - PullRequest
0 голосов
/ 11 апреля 2011

Привет, я новичок в программировании для iphone, я использую XML Parser для получения данных, я храню данные в NSMutable Array.(я могу видеть данные в консоли, используя NSLog) Я не могу отобразить данные в представлении таблицы.Пожалуйста, помогите мне.вот мой код.

#import <UIKit/UIKit.h>
#import "NamazTime.h"
#import <Foundation/NSXMLParser.h>
#import "NamazTimeController.h"

@protocol NSXMLParserDelegate;


@interface NamazTimeController : UITableViewController <NSXMLParserDelegate> {

    NSMutableArray *colorNames;

}
@property (nonatomic, retain) NSMutableArray *colorNames;
- (void)loadNamTime;

@end




//
//  NamazTimeController.m
//  MCVNamaz
//
//  Created by Andy on 28/03/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "NamazTimeController.h"
#import "WSNamaz.h"
#import "NamazTime.h"

@implementation NamazTimeController
@synthesize colorNames;



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

//NamazTime *namTime = [[NamazTime alloc] init];



- (id)init {
    //Call the superclass's designated initializer
    [super initWithNibName:nil bundle:nil];
    //Get the tab bar item
    UITabBarItem *tbi = [self tabBarItem];
    //Give it a label
    [tbi setTitle: @"Today"];
    UIImage *i = [UIImage imageNamed:@"Time.png"];
    [tbi setImage:i];


//  [arrWeek removeAllObjects];

    [[self tableView] reloadData];
    return self;
}

#pragma mark -
#pragma mark View lifecycle

/*
- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];    

    NSLog(@"view will appear works!!!!!");


    [super viewWillAppear:animated];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source
/*
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
//    return <#number of sections#>;
}

*/

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


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    /*
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: @"UITableViewCell"] autorelease];
    }
//  [[cell textLabel] setText:[arrWeek objectAtIndex:[indexPath row]]];
    return cell;
     */
    static NSString *CellIdentifier = @"Cell";

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

    // Configure the cell.
    cell.textLabel.text = [self.colorNames objectAtIndex: [indexPath row]];

    return cell;


}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
    // ...
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
    */
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidLoad{
    NSLog(@"array view load called");
//  self.colorNames = [[NSMutableArray alloc] initWithObjects: @"colorNames", nil];
    [super viewDidLoad];
//  NamazTime *nt = [[NamazTime alloc] init];
//  self.colorNames = [nt loadNamTime];

//  WSNamaz *wsnamaz = [[WSNamaz alloc] init];
//  self.colorNames = wsnamaz ver
//  [wsnamaz verifyXML];
    //NamazTimeController *ntcc = [[NamazTimeController alloc] init];
//  self.colorNames = wsnamaz.namazXmlArray;

    //self.colorNames = [[NSMutableArray alloc] initWithObjects:colorNames, nil];
    self.colorNames = [[NSMutableArray alloc] init];
    //NamazTime *nt = [[NamazTime alloc] init];
    //self.colorNames = [nt loadNamTime];

    //NamazTimeController *wtcObject = [[NamazTimeController alloc] init];
    //[wsObject verifyXML];

    //self.colorNames = [[NSMutableArray alloc] init];

    //self.colorNames = [nt loadNamTime];
//  [wsnamaz verifyXML];
    //  displayText.text = @"text";
}

- (void)viewDidUnload {
    self.colorNames = nil;

    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)loadNamTime
{
    NamazTime *nt = [[NamazTime alloc] init];
    self.colorNames = [nt loadNamTime];
    for (int i = 0; i < 5; i++)
        NSLog (@"Element of color names  in the namaz time controller %i = %@", i, [colorNames objectAtIndex: i]);

    //[[self tableView] reloadData];
    [self viewDidLoad];


}   


@end

1 Ответ

1 голос
/ 11 апреля 2011

Здесь куча вопросов.Надеюсь, что это поможет вам, по крайней мере, запустить ваше приложение:

  1. Общий комментарий, чтобы получить лучшие ответы на stackoverflow: очистите ваш код, вставьте только те части, которые относятся к вашему вопросу, иотформатируйте его правильно.Образец не был отформатирован как блок кода и содержит так много закомментированных разделов, что нам трудно помочь.

  2. init не правильно инициализирует экземпляр.Во-первых, вам нужно использовать self = [super initWithNibName:nil bundle:nil].Во-вторых, я бы обернул все остальное до return self в if (self) {}, чтобы он выполнялся только в случае успешной инициализации.

  3. Также в init представления не загружаются в initXXX методы, поэтому вы должны удалить [[self tableView] reloadData].

  4. В viewWillAppear вы вызываете [super viewWillAppear] дважды.Вероятно, не вредно, но определенно не обязательно.Поскольку в этом методе вы ничего не делаете, я бы полностью удалил его.

  5. Что касается загрузки данных в таблицу, вам не нужно вызывать reloadDataпри первой загрузке представления b / c tableView загружается само при первом отображении.Вам нужно вызывать [tableView reloadData] всякий раз, когда модель данных требует изменений.В вашем случае вам нужно попытаться сделать это в loadNamTime.Вы не должны звонить [self viewDidLoad], так как это неверно и может иметь нежелательные побочные эффекты.Как правило, никогда не следует вручную вызывать viewDidLoad, это системное сообщение, основанное на фактически загруженном представлении.Раскомментируйте строку [[self tableView] reloadData].

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