0

我有一个声明NSMutableArray为. 我想复制到.FirstViewControllerfirstArraysecondArrayfirstArray

在 SecondViewController 中,

Self.FirstViewController.firstArray = self.secondArray;

当我尝试NSLogfirstArray.count 中获取 .count 时FirstViewController,它显示 0。它应该在数组中有两个对象

任何人都可以就此提出建议吗?

4

3 回答 3

2

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

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

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

单例示例:

static MySingleton *sharedSingleton;

    + (void)initialize
    {
        static BOOL initialized = NO;
        if(!initialized)
        {
            initialized = YES;
            sharedSingleton = [[MySingleton alloc] init];
        }
    }
于 2013-05-21T13:14:41.827 回答
0

在将引用传递给第一个视图控制器时,看起来第二个数组已经被释放,或者第一个视图控制器本身已经被取消。如果第一个是正确的,那么您可能需要一个不同的模型对象来保存您的数据,而不是将其保存在应用程序的控制器层中。如果不是这种情况,那么您可能需要考虑直接复制。最简单的方法是在接口文件中将 firstArray 属性声明为关键字 copy 而不是 strong 。

如果您确实需要在应用程序的模型层中保留数据,那么正如 EXEC_BAD_ACCESS(好名字!)指出的那样,单例模式对象确实是实现此目的的一种方式。编写单例的一种稍微更现代(虽然功能等效)的方式如下。

@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 initialize] 多次,尽管我从不建议这样做)。

于 2013-05-21T13:28:41.637 回答
0

您还可以利用NSNotificationCenter

第二视图控制器.m

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

第一视图控制器.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方法时删除通知。

希望能帮助到你。

于 2013-05-21T13:32:33.420 回答