2013-05-21 85 views
0

我有一个NSMutableArrayFirstViewController宣布为firstArray。 我想将secondArray复制到firstArray将NSMutableArray从一个viewcontroller复制到另一个viewcontroller?

在SecondViewController,

Self.FirstViewController.firstArray = self.secondArray; 

当我试图从FirstViewControllerNSLogfirstArray .Count中,它显示为0。它应该有阵列

任何人都可以在这个建议中有两个对象?

+0

请发布代码,看来secondArray是空的。无论如何,如果你想复制,我建议你使用“arrayWithArray”,你做的不是副本 –

+0

http:// stackoverflow。COM /问题/ 5210535 /传递数据 - 视图 - 控制器之间-/ 9736559#9736559 –

回答

2

您可以选择这个解决方案之一:

  1. 辛格尔顿
  2. 传递数据ViewControllers代表团

    之间

你可以找到你需要在这里的所有信息: https://stackoverflow.com/a/9736559/1578927

单身人士例子:

static MySingleton *sharedSingleton; 

    + (void)initialize 
    { 
     static BOOL initialized = NO; 
     if(!initialized) 
     { 
      initialized = YES; 
      sharedSingleton = [[MySingleton alloc] init]; 
     } 
    } 
0

它看起来像第二个数组已被释放,当传递引用到第一个视图控制器,或第一个视图控制器本身已经被删除。如果第一个是真的,那么您可能需要一个不同的模型对象来保存数据,而不是将其保存在应用程序的控制器层中。如果情况并非如此,那么您可能需要考虑直接复制。这样做的最简单方法是将firstArray属性声明为关键字副本,而非强大的接口文件。

如果您确实需要将数据保存在应用程序的模型层中,那么单例模式对象确实是实现此目的的一种方式,因为EXEC_BAD_ACCESS(nice name!)指出。一个稍微更现代的(虽然功能上等价)写单例的方式如下。

@interface MySingleton : NSObject 

@property (strong, readwrite) id myData; 

+ (id)sharedSingleton 

@end 

@implementation MySingleton 

+ (id)sharedSingleton 
{ 
    static MySingleton *singleton = nil; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    singleton = [[MySingleton alloc] init]; 
    // Do other setup code here. 
    }); 
    return singleton; 
} 

@end 

的使用注意事项dispatch_once的 - 这使得肯定的是,静态单只能创建一次(而从技术上讲,你可以调用+ [NSObject的初始化]多次,你感觉像手动,但我会从不建议这样做)。

0

您也可以利用NSNotificationCenter

SecondViewController.m的

[[NSNotificationCenter defaultCenter] postNotificationName:@"arrayFromSecondVC" object:secondArray]; 

FirstViewController.m

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(populateArray:) name:@"arrayFromSecondVC" object:nil]; 

} 

-(void)populateArray:(NSNotification *)notif 
{ 


self.firstArray = [notif object]; 

} 

,并删除该通知时,viewUnload或didRecieveMemoryWarning方法。

希望它有帮助。

相关问题