2014-07-16 19 views
0

我是編程新手,在將對象從一個VC移動到另一個時遇到問題。在視圖控制器之間移動對象

我的第二個VC有NSArray * objects。第三VC有NSMutableArray *產品。我有模態SEGUE 2 - > 3 這裏是我的賽格瑞方法:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ 
if ([segue.identifier isEqualToString:@"Products segue"]) { 
    ProductsViewController*pvc = segue.destinationViewController; 
    pvc.products = [self.objects mutableCopy]; 
} 

}

ProductsViewController我創建了幾個對象:

-(IBAction)addSomeObjects { 
products = [NSMutableArray new]; 
[products addObject:@"Cola"]; 
[products addObject:@"Pepsi"]; 
[products addObject:@"Fanta"]; 
[products addObject:@"Red bull"]; 
[products addObject:@"Monster"]; 

如果我的NSLog我IBAction方法,產品成功添加我的對象,但當我dissmissViewController我的對象數組是空的。

感謝您的任何幫助。

+1

This:'pvc.products = [self.objects mutableCopy]'創建一個新的可變數組,它包含與'self.objects'相同的對象。這:'products = [NSMutableArray new]'創建一個新的空數組。你已經證明,它不會改變'self.objects'。 –

+0

那麼,我該怎麼做才能改變我的self.objects? –

+0

可能重複[在視圖控制器之間傳遞數據](http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) –

回答

1

M. Koptak。歡迎來編程。

在這個例子中,我建議你創建一個模型來管理產品。模型是表示數據的類。在這個例子中,創建一個類來表示產品的集合。爲此,我將其稱爲目錄。

// In Catalog.h 
@interface Catalog : NSObject 
@property (nonatomic, readonly) NSMutableArray *products; 
@end 

// In Catalog.m 
@implementation Catalog 
- (id)init 
{ 
    self = [super init]; 
    if (self) { 
     _products = [NSMutableArray array]; 
    } 
} 
@end 

現在,我具有可以管理產品的一類,我需要在第一視圖控制器和ProductsViewController具有(的Catalog型)catalog性質。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if ([segue.identifier isEqualToString:@"Products segue"]) { 
     ProductsViewController *pvc = segue.destinationViewController; 
     pvc.catalog = self.catalog; // Pass the catalog between the view controllers. 
    } 
} 

- (void)viewDidLoad 
{ 
    … 
    if (self.catalog == nil) // Make sure an instance of `Catalog` has been created! 
     self.catalog = [[Catalog alloc] init]; 
    … 
} 

最後,在ProductsViewController

- (IBAction)addSomeObjects 
{ 
    [self.catalog.products addObject:@"Cola"]; 
    [self.catalog.products addObject:@"Pepsi"]; 
    [self.catalog.products addObject:@"Fanta"]; 
    [self.catalog.products addObject:@"Red bull"]; 
    [self.catalog.products addObject:@"Monster"]; 
} 

現在,當您關閉ProductsViewController,第一個視圖控制器將所有的新產品。

注意:這是如何共享數據的第一步。它跳過適當的類名,數據保護和數據驗證,但它讓你開始。

+0

感謝您向我展示更好的解決方案。它工作正常,但我需要在我的NSArray中的對象:)它與我的搜索欄一起工作,所以我需要用它填充它以在我的搜索欄表格視圖中顯示對象。 –

+0

噢,我明白了。在viewWillAppear我已經把self.objects = self.catalog.products;現在它終於起作用了! :)非常感謝你 –

相關問題