2012-01-03 52 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下找到。

希望我能幫上忙!

相關問題