【发布时间】:2016-06-05 05:50:21
【问题描述】:
我一直在尝试从我认为是我已经实现的单例类中实现一个全局 NSMutableArray。
我可以进入ViewController#2,向数组中添加和删除对象。
但是,当我离开 ViewController #2 并返回时,数据不会保留,并且我有一个包含 0 个对象的数组。
你认为我做错了什么?
.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;
}
查看控制器 #2
GlobalArray* myGlobalArray;
myGlobalArray = [[GlobalArray alloc] init];
//Various add and remove code
感谢您的意见。
【问题讨论】:
-
您不是在创建单例实例并访问共享实例;您只是每次都创建一个新实例。见galloway.me.uk/tutorials/singleton-classes
-
有很多关于如何在 Objective-C 中正确创建单例的答案。
标签: ios objective-c arrays xcode