cellForRowAtIndexPath не вызывается - PullRequest
1 голос
/ 06 ноября 2011

У меня были проблемы со связью между двумя взглядами.Моей целью было добавить новый объект в мой NSMutableArray.Спасибо милым людям в stackoverflow, которые были исправлены.Теперь у меня есть другая проблема.Несмотря на то, что я могу добавить объект к своему NSMutableArray, таблица не обновляется, чтобы заполнить ее новыми данными.Вот некоторый код:

FirstViewController.h

@interface FirstViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>{  
    IBOutlet UITableView *mytableview;  
    NSMutableArray *mytableinfo;  
@property (nonatomic,retain) IBOutlet UITableView *mytableview;  
@property (nonatomic,retain) NSMutableArray *mytableinfo;`

FirstViewController.m

-(IBAction)addShift:(id)sender{
    SecondViewController *secondViewController = [[SecondViewController alloc]init];
    [self presentModalViewController:secondViewController animated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    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 =[mytableinfo objectAtIndex:indexPath.row];
    NSLog(@"Data was written to table");
    return cell;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    mytableinfo = [[NSMutableArray alloc]init];
    mytableview = [[UITableView alloc]init];
    [mytableinfo addObject:@"Hello world1"];
    [self.mytableview reloadData];
}
- (void)viewDidLoad
{
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addShift:)];
    self.navigationItem.rightBarButtonItem = addButton;    
    [super viewDidLoad]; 
    UIBarButtonItem *refresh = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadTableData:)];
    self.navigationItem.leftBarButtonItem = refresh;
    mytableinfo = [[NSMutableArray alloc]init];
    [mytableinfo addObject:@"First Shift"];
    [self.mytableview reloadData];
    // Do any additional setup after loading the view from its nib.
}

SecondViewController.m

#import "SecondViewController.h"
#import "FirstViewController.h"

-(IBAction)saveShift:(id)sender{
    FirstViewController *firstViewController = [[FirstViewController alloc]init];
    firstViewController.mytableinfo = [[NSMutableArray alloc]init];
    [firstViewController.mytableinfo addObject:@"SecondViwController Dismissed"];
    NSLog(@"%@",[firstViewController.mytableinfo objectAtIndex:0]);
    [self dismissModalViewControllerAnimated:YES];
}

Поэтому, когда saveShift называется Iследует вернуться к основному виду, что я делаю, а затем снова заполнить мой tableview.Как будто я выхожу из небольшой проблемы только для того, чтобы прыгнуть в другую - не очень хорошее чувство!Ура, Сэм

Ответы [ 3 ]

2 голосов
/ 06 ноября 2011

в вашем saveShift:(id)sender методе вам нужно много кода. Просто сделайте следующее:

[self.myTableInfo addObject:@"SecondViewConroller dimissed"];
[self dismissModalViewControllerAnimated:YES];

В этом коде я предполагаю, что вы передали ссылку на свой NSMutableArray в вашем secondView.

Я помню ваш пост из NSMutableArray, и вы представляете SecondView из FirstView (если у меня хорошая память).
Но в вашем коде, в saveShift secondView, вы в настоящее время создаете brand new FirstView, который отличается от того, откуда вы пришли. Поэтому, когда вы отклоняете модальное представление, ваш «совершенно новый» firstView теряется, и вы возвращаетесь к своему первоначальному firstView. И этот последний не слышал о вашем объекте.


Привет, Сэм,
посмотрите на последний ответ, который я дал вам в вашей ветке NSMutableArray, там есть почти все, что вам нужно для решения этой проблемы.


ОК, вот еще быстрое исправление, чтобы оно могло работать

//  SecondViewController.m
#import "SecondViewController.h"
#import "FirstViewController.h"
@implementation SecondViewController
@synthesize dateformatter,mydatepicker,startingTime;
//  HERE Add a new property that match this and a variable in the .h
@synthesize array4Test;
//   HERE make an init that will make this UIViewController know about your NSMutableArray
- (id)initWithMutableArray:aMutableArray
{
self = [self initWithNibName:nil bundle:nil];
if (self)
{
    self.array4Test = aMutableArray;
}
return  self;
}
- (void)dealloc 
{    
//  HERE clean up
self.array4Test = nil;
[super dealloc];
}
-(IBAction)saveShift:(id)sender{
//    HERE remove this code
//FirstViewController *firstViewController = [[FirstViewController alloc]init];
//[firstViewController.mytableinfo addObject:@"Hello world"];
//NSLog(@"%@",[firstViewController.mytableinfo objectAtIndex:0]);
//    HERE add an object to the mutableArray that is store in your firstViewController, the one you've passed the reference in
[self.array4Test addObject:@"This is a String"];
[self dismissModalViewControllerAnimated:YES];
}

Я думаю, что я только что добавил NSLog () в этом.

//  FirstViewController.m
#import "FirstViewController.h"
#import "SecondViewController.h"

@implementation FirstViewController
@synthesize mytableinfo,mytableview;
@synthesize goneToOtherView;
-(IBAction)addShift:(id)sender{
SecondViewController *secondViewController = [[SecondViewController alloc] initWithMutableArray:self.mytableinfo];
[self presentModalViewController:secondViewController animated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.mytableview reloadData];
NSString *aString = [mytableinfo lastObject];
if (aString)
{
    NSLog(@"This just came back from the second View\n%@", aString);
}
}
2 голосов
/ 06 ноября 2011

Здесь есть как минимум пара проблем.

Первая проблема: вы создаете совершенно новый FirstViewController в saveShift: вместо добавления объекта к существующему FirstViewController.Это не сработает.В addShift:, когда вы создаете secondViewController, вы должны передать существующий FirstViewController в качестве параметра, например так:

SecondViewController *secondViewController = [[SecondViewController alloc] initWithFirstViewController:self];

Вам нужно изменить SecondViewController, чтобы получить initWithFirstViewController: метод, который должен хранить FirstViewController в свойстве с именем firstViewController.

Вторая проблема: вы не говорите табличному представлению о новой строке.Вы должны добавить метод к FirstViewController:

- (void)reallyAddShift:(NSString *)newShift
{
    [self.mytableinfo addObject:newShift];
    NSIndexPath ip = [NSIndexPath indexPathForRow:[self.mytableinfo count]-1 inSection:0];
    [self.mytableview insertRowsAtIndexPaths:[NSArray arrayWithObject:ip] withRowAnimation: UITableViewRowAnimationFade];
}

Затем, в saveShift:, вы можете просто сделать это:

-(IBAction)saveShift:(id)sender{
    [self.firstViewController reallyAddShift:@"SecondViwController Dismissed"];
    [self dismissModalViewControllerAnimated:YES];
}
1 голос
/ 06 ноября 2011

Назначение просто mytableinfo = [[NSMutableArray alloc]init]; не сохранит его. Сделай это self.mytableinfo = [[NSMutableArray alloc]init];.

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