2012-01-03 63 views
0

我需要使用视图控制器类中的SecondViewController的按钮来删除数组。从C-Objective中的另一个类中删除一个NSMutableArray?

目前,我有这样的:

- (IBAction)deleteArrayFromSeconViewController:(id)sender // is the Button which should       
                  // delete the array 
{ 
    self.textLabel2.text = @"";       // this work fine 
    ViewController *vc = [[ViewController alloc]init]; 
    [vc.textViewArray removeAllObjects];     // do not remove the objects? 

} 

我应该怎么做超车从SecondViewControllerClass在ViewControllerClass订单?

我也试过这个在SecondViewControllerClass:

- (IBAction)deleteArrayFromSeconViewController:(id)sender 
{ 
    self.textLabel2.text = @""; 

    ViewController *vc = [[ViewController alloc]init]; 
    [vc deleteTheArray]; 

} 

来调用ViewControllerClass此功能:

- (void) deleteTheArray 
{ 
    [textViewArray removeAllObjects]; 
} 
+5

你可能需要一个指向当前存在的“另一个视图控制器”,而不是创造新的。 – Krizz 2012-01-03 17:46:16

+1

在您调用的另一个ViewController上创建一个方法来清除该数组也可能是值得的,以便它可以选择运行任何内务代码,而不是将数据从其下拉出来。即使现在没有必要的内务管理,它也会使未来的重构更容易:) – matthias 2012-01-03 17:49:46

回答

1

我不能肯定,这是做到这一点的最好办法,但您可以在第一个视图控制器中发布自定义NSNotification,然后在第二个视图控制器中选择它。代码示例:

//Post in your first view controller when wanting to delete the array 
[[NSNotificationCenter defaultCenter] postNotificationName:@"DeleteArrayNotification" object:nil userInfo:nil /*include any items your reciever might wish to access*/]; 

,然后在你的第二个视图控制器,你可以添加自己作为-(void)awakeFromNib方法的观察员。把你的清醒,从笔尖方法:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteArrayNotification:) name:@"DeleteArrayNotification" object:nil]; 

,然后实现deleteArrayNotification:方法:

- (void)deleteArrayNotification:(NSNotification *)notification { 
[array removeAllObjects]; 
[array release]; //Delete this line if your project is using ARC 
} 

我高度怀疑,这是良好的编码习惯来实现NSNotification这样的,但我认为它可能是有用的!

更多信息可在Apple开发人员文档的NSNotificationNSNotificationCenter下找到。

希望我能帮上忙!