当从另一个视图控制器调用嵌入式函数时,Tableview reloaddata不起作用

时间:2013-12-17 14:03:59

标签: ios iphone uitableview

我正在经历一个奇怪的tableview行为,我正在构建一个应用程序,当点击ADD时会出现一个模态视图控制器,它是UATitledModalPanel的子类,我只是提供一些文本字段来插入用户的信息。

当他们点击提交时,数据将被发送到mainviewcontroller的函数,该函数将数据保存到DataBase并尝试重新加载我以编程方式创建的tableview。但是在上面的过程中,tableview不会重新加载。但是如果从viewcontroller中的buton执行相同的过程,它会正确地执行此操作。下面是我的视图控制器的代码。

ViewController.h

 @interface ViewController :      UIViewController<UAModalPanelDelegate,UITextFieldDelegate,UITextViewDelegate,UITableViewData Source,UITableViewDelegate>{
DataClass *dataOfValue;
}
@property(strong,nonatomic)UITableView *table;
-(void)reloadDatas;
-(void)insertData:(NSString *)gettingData;

ViewController.m

@interface ViewController (){
NSMutableArray *data;
DataClass *dataclass;
}

@end

@implementation ViewController
@synthesize table;
static NSString *CellIdentifier = @"CellIdentifier";

- (void)viewDidLoad
{
[super viewDidLoad];
table = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height-64.0f) style:UITableViewStylePlain];
[self.view addSubview:table];
[table registerClass:[CustomCell class] forCellReuseIdentifier:CellIdentifier];
self.navigationItem.title = @"Scheduler";
self.table.delegate = self;
self.table.dataSource = self;
//self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIImageView *infoimg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"detail.png"]];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoimg];

UITapGestureRecognizer *infotap = [[UITapGestureRecognizer alloc]
                               initWithTarget:self
                               action:@selector(addAction:)];
[infotap setAccessibilityLabel:@"infotap"];
infotap.numberOfTapsRequired = 1;

[infoimg addGestureRecognizer:infotap];

UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"add.png"]];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:img];

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                               initWithTarget:self
                               action:@selector(addAction:)];
[tap setAccessibilityLabel:@"tap"];
tap.numberOfTapsRequired = 1;

[img addGestureRecognizer:tap];

table.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"table_background.jpg"]];

//UIImage *img = [[UIImage alloc] i]
 table.separatorColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"navigation_bar.jpg"]];

[self openDataBase];

}

- (void)openDataBase{
data = [NSMutableArray new];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"callsmsDB.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
FMResultSet *res = [database executeQuery:@"SELECT * FROM data"];
int i = 0;
while ([res next]) {
    i++;
    //NSLog(@"%@",[res stringForColumn:@"status"]);
    dataclass = [[DataClass alloc] init];
    dataclass.identifier = [NSNumber numberWithInt:[res intForColumn:@"id"]];
    dataclass.number = [res stringForColumn:@"number"];
    dataclass.date = [res stringForColumn:@"date"];
    dataclass.type = [res stringForColumn:@"type"];
    dataclass.description = [res stringForColumn:@"description"];
    dataclass.status = [res stringForColumn:@"status"];
    [data addObject:dataclass];

}
NSLog(@"The size of the array is %d",[data count]);
NSLog(@"The value of is %d",i);
[self.table performSelectorOnMainThread:@selector(reloadData) withObject:self.table waitUntilDone:YES];

[database close];
}

- (void)addAction:(id)sender{
UIGestureRecognizer *infotag = (UIGestureRecognizer *) sender;
NSString *info = infotag.accessibilityLabel;
if([info isEqualToString:@"infotap"]){
    //NSLog(@"About app");
    //[self performSegueWithIdentifier:@"appinfo" sender:self];
    /*AboutApp *nextController = [[self storyboard] instantiateViewControllerWithIdentifier:@"aboutapp"];
    [UIView beginAnimations:@"animation" context:nil];
    [self.navigationController pushViewController: nextController animated:NO];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
    [UIView commitAnimations];*/
    [self performSelectorOnMainThread:@selector(openDataBase) withObject:self waitUntilDone:YES];

   }else{
    [self showModalPanel:sender];

   }
   }

  -(void)showModalPanel:(id)sender{

UAExampleModalPanel *modalPanel = [[UAExampleModalPanel alloc] initWithFrame:self.view.frame title:@"Schedule a Task"] ;

   int blocksDelegateOrNone = arc4random() % 3;

if (0 == blocksDelegateOrNone) {
    // The block is responsible for closing the panel,
    //   either with -[UAModalPanel hide] or -[UAModalPanel hideWithOnComplete:]
    //   Panel is a reference to the modalPanel
    modalPanel.onClosePressed = ^(UAModalPanel* panel) {
        // [panel hide];
        [panel hideWithOnComplete:^(BOOL finished) {
            [panel removeFromSuperview];
        }];
        UADebugLog(@"onClosePressed block called from panel: %@", modalPanel);
    };

    //   Panel is a reference to the modalPanel
    modalPanel.onActionPressed = ^(UAModalPanel* panel) {
        UADebugLog(@"onActionPressed block called from panel: %@", modalPanel);
    };

    UADebugLog(@"UAModalView will display using blocks: %@", modalPanel);

    // USE DELEGATE
         } else if (1 == blocksDelegateOrNone) {
    // Add self as the delegate so we know how to close the panel
    modalPanel.delegate = self;

    UADebugLog(@"UAModalView will display using delegate methods: %@", modalPanel);

    // USE NOTHING
        } else {
    // no-op. No delegate or blocks
    UADebugLog(@"UAModalView will display without blocks or delegate methods: %@", modalPanel);
}

// Add the panel to our view
[self.view addSubview:modalPanel];

// Show the panel from the center of the button that was pressed
[modalPanel showFromPoint:self.view.bounds.origin];
    }
   -(void)insertData:(NSString *)gettingData{
//NSLog(@"data is %@",gettingData);
    NSString *number;
    NSString *date;
    NSString *type;
    NSString *description;
    NSString *status;
    NSArray *myString = [gettingData componentsSeparatedByString:@"@@"];
//NSLog(@"%@",myString);
number = [myString objectAtIndex:0];
date = [myString objectAtIndex:1];
type = [myString objectAtIndex:2];
description = [myString objectAtIndex:3];
status  = @"active";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"callsmsDB.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
BOOL b = [database executeUpdate:@"INSERT INTO data(number,date,type,description,status) VALUES (?,?,?,?,?)",number, date, type, description,status];
  if(b)
    NSLog(@"Successfully inserted.");
    int i = [database lastInsertRowId];
    NSLog(@"last inserted id is %i",i);
    [database close];
   [self openDataBase];


   }

  - (void)didReceiveMemoryWarning
 {
 [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
 }

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"The value of count of data is %d",[data count]);
UIImage *typeImage;
CustomCell *cell;
if(cell == nil)
    cell =  (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure Cell
DataClass *recent = [data objectAtIndex:indexPath.row];
//NSLog(@"jjj %@",recent.description);
if ([recent.type isEqualToString:@"call"]) {
    typeImage = [UIImage imageNamed:@"call.png"];
}else{
    typeImage = [UIImage imageNamed:@"sms.png"];
}
[cell.mylabel setText:recent.number];
[cell.corsms setImage:typeImage forState:UIControlStateNormal];
UIImage *delImage = [UIImage imageNamed:@"delete.png"];
[cell.detail setImage:delImage forState:UIControlStateNormal];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if([recent.status isEqualToString:@"Active"]){
    [cell.myswitch setOn:YES];
}else{
    [cell.myswitch setOn:NO];
}
[cell.myswitch addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
return cell;
}


 - (void)changeSwitch:(id)sender{

NSString *status;
RCSwitchOnOff *sw = (RCSwitchOnOff *)sender;
CustomCell *custcell = (CustomCell *)sw.superview.superview;
UITableView *tableview = (UITableView *)custcell.superview;
NSInteger rowOfTheCell = [[tableview indexPathForCell:custcell] row];
//NSLog(@"%i",rowOfTheCell);
if([sw isOn]){
    status = @"Active";
}else{
    status = @"Inactive";
}
NSLog(@"%@",status);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"callsmsDB.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
[database executeUpdate:@"UPDATE data SET status = ? WHERE id = ?",status,[[data objectAtIndex:rowOfTheCell] identifier]];
[database close];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section          {
NSLog(@"Number of rows in section = %d",[data count]);
return [data count];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
 }
ModalViewController中的

我创建了一个ViewController实例并调用了insertData,但是它没有重新加载表。但是,如果我将一个条形按钮附加到我的导航栏并调用表重新加载,它确实有效。

我不想制作刷新按钮来重新加载表格。

1 个答案:

答案 0 :(得分:0)

您不应该在ModalViewController中创建ViewController的实例。这是不对的。相反,您可以创建协议并委派通知。 您可以从以下链接获取更多详细信息。

http://www.tutorialspoint.com/ios/ios_delegates.htm