繁体   English   中英

将NSMutableArray从一个viewcontroller复制到另一个viewcontroller?

[英]Copying of NSMutableArray from one viewcontroller to another viewcontroller?

我在FirstViewController有一个NSMutableArray声明为firstArray 我想将secondArray复制到firstArray

在SecondViewController中,

Self.FirstViewController.firstArray = self.secondArray;

当我从FirstViewController尝试NSLog firstArray FirstViewController ,它显示0.它应该在数组中有两个对象

有人可以就此提出建议吗?

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

  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];
        }
    }

看起来第二个数组在将引用传递给第一个视图控制器时已经被释放,或者第一个视图控制器本身已被缩小。 如果第一个为真,那么您可能需要一个不同的模型对象来保存数据,而不是将其保存在应用程序的控制器层中。 如果不是这种情况,那么您可能需要考虑直接复制。 最简单的方法是在接口文件中将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]多次,尽管我从不建议这样做)。

您也可以利用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方法时删除通知。

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM