Objective-C定义一个供多个ViewController使用的全局数组 [英] Objective-C Defining a Global Array for use by several ViewControllers

查看:111
本文介绍了Objective-C定义一个供多个ViewController使用的全局数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从我认为已实现的单例类中实现全局NSMutableArray。

I've been trying to implement a global NSMutableArray from what I think to be a singleton class that I've implemented.

我可以输入ViewController#2,添加并删除对象到数组。

I can enter ViewController # 2, add and remove objects to the array.

但是,当我离开ViewController#2并返回时,数据不会持久存在,并且我有一个包含0个对象的数组。

However, when I leave ViewController #2 and come back, the data does not persist, and I have an array with 0 objects.

您认为我做错了什么?

.h

//  GlobalArray.h
@interface GlobalArray : NSObject{
    NSMutableArray* globalArray;
}

+(void)initialize;

.m

#import "GlobalArray.h"

@implementation GlobalArray

static GlobalArray* sharedGlobalArray;

NSMutableArray* globalArray;

+(void)initialize{
    static BOOL initalized = NO;
    if(!initalized){
        initalized = YES;
        sharedGlobalArray = [[GlobalArray alloc] init];
    }
}

- (id)init{
    if (self = [super init]) {
        if (!globalArray) {
            globalArray = [[NSMutableArray alloc] init];
        }
    }
    return self;
}

View Controller#2

View Controller #2

GlobalArray* myGlobalArray;
myGlobalArray = [[GlobalArray alloc] init];

//Various add and remove code

感谢您的输入。

推荐答案

以下是在应用程序级别全局共享数据的最佳方法。 Singleton类是关键。 Singleton仅初始化一次,其余时间返回共享数据。

Following is best approach to share data Globally at Application level. Singleton Class is a key. Singleton is only initialised once, rest of times shared data is returned.

@interface Singleton : NSObject
@property (nonatomic, retain) NSMutableArray * globalArray;
  +(Singleton*)singleton;
@end

@implementation Singleton
@synthesize globalArray;
+(Singleton *)singleton {
    static dispatch_once_t pred;
    static Singleton *shared = nil;
    dispatch_once(&pred, ^{
        shared = [[Singleton alloc] init];
        shared.globalArray = [[NSMutableArray alloc]init];
    });
    return shared;
}
@end

以下是访问/使用共享数据的方式

Following is the way to access/use shared data.

NSMutableArray * sharedData = [Singleton singleton].globalArray;

这篇关于Objective-C定义一个供多个ViewController使用的全局数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆