NSMutable 单例问题
我想获得一些帮助来整理我为实现 NSMutableArray 单例而想出的代码。
.h 文件
@interface MySingleton : NSObject {
NSMutableArray *globalArray;
}
+ (MySingleton *)instance;
- (NSMutableArray *) getArray;
- (void) addArray:(NSObject *)arrayToAdd;
- (id) init;
.m file
@implementation MySingleton
- (id) init
{
self = [super init];
globalArray = [[NSMutableArray alloc] init];
return self;
}
+ (MySingleton *)instance {
static MySingleton *instance;
@synchronized(self) {
if(!instance) {
instance = [[MySingleton alloc] init];
}
}
return instance;
}
- (NSMutableArray *) getArray{
return globalArray;
}
- (void) addArray:(NSMutableArray *)arrayToAdd
{
[globalArray addObject:arrayToAdd];
}
someviewcontroller.m
MySingleton *prodInstance = [MySingleton instance];
[prodInstance addArray:tmpArray];
NSLog(@"cnt tmpArray %i",[tmpArray count]);
NSLog(@"cnt singleton %i",[[prodInstance getArray] count]);
控制台将显示计数 3 和 1。
我认为 [prodInstance getArray] 将与 tmpArray 相同。
谢谢
I would like to get some help to sort out the code I've come up with to implement a NSMutableArray singleton.
.h file
@interface MySingleton : NSObject {
NSMutableArray *globalArray;
}
+ (MySingleton *)instance;
- (NSMutableArray *) getArray;
- (void) addArray:(NSObject *)arrayToAdd;
- (id) init;
.m file
@implementation MySingleton
- (id) init
{
self = [super init];
globalArray = [[NSMutableArray alloc] init];
return self;
}
+ (MySingleton *)instance {
static MySingleton *instance;
@synchronized(self) {
if(!instance) {
instance = [[MySingleton alloc] init];
}
}
return instance;
}
- (NSMutableArray *) getArray{
return globalArray;
}
- (void) addArray:(NSMutableArray *)arrayToAdd
{
[globalArray addObject:arrayToAdd];
}
someviewcontroller.m
MySingleton *prodInstance = [MySingleton instance];
[prodInstance addArray:tmpArray];
NSLog(@"cnt tmpArray %i",[tmpArray count]);
NSLog(@"cnt singleton %i",[[prodInstance getArray] count]);
The console will display counts 3 and 1.
I thought [prodInstance getArray] will be the same as the tmpArray.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您的 addArray 方法将 tmpArray 放入 globalArray 中,这显然不是您想要的。
我认为根本没有任何理由需要
addArray
——只需调用getArray
来获取全局数组,并使用它即可。例如:The problem is your
addArray
method is puttingtmpArray
insideglobalArray
, which is apparently not what you want.I don't think there's really any reason to have
addArray
at all -- just callgetArray
to get the global array, and work with that. For example:在
-addArray:
中,您将数组参数arrayToAdd
添加为全局数组中的单个元素。看起来您想添加数组参数的所有元素,因此替换为
Also,由于参数不需要是可变数组,请考虑将参数类型更改为
NSArray *
。In
-addArray:
, you’re adding the array argumentarrayToAdd
as a single element in the global array. It looks like you want to add all the elements of the array argument instead, so replacewith
Also, since the argument doesn’t need to be a mutable array, consider changing the parameter type to
NSArray *
.