0

我对 NSMutablearray addobject 感到困惑,我尝试像这样制作共享实例 nsmutable 数组:

1.共享实例

+ (netra*)someInstance
{
    if (sharedObject == nil) {
        sharedObject = [[super allocWithZone:NULL] init];
    }
    return sharedObject;
}

1.1 插入方法

+(void) setStock:(NSInteger *)stock{
    // Ensure we are using the shared instance
    netra *shared = [netra sharedInstance];
    [shared.stockInits addObject:stock];

}

1.3 调用nsmutablearray的方法

+(NSMutableArray *) getStock{
    // Ensure we are using the shared instance
    netra *shared = [netra sharedInstance];
     return shared.stockInits ;
}

2.插入方法

-(void) some{
for(int x=0;x<=1000;x++){
    [netra setStock:i];
 }
}

3.从其他控制器调用的方法

for (int x=0; x<=[netra getStock].count;x++){
nslog (@"i-------->%d",x);
}

日志应该显示 0-1000 对???但为什么它总是返回 1000......1000 ?我的代码有什么问题吗?

4

1 回答 1

1

首先,我将创建一个 getInstance 方法,例如:

@implementation SinglentonObject{
    NSMutableArray *array;
}

+ (id)getInstance {
    static SinglentonObject *instance = nil;
    @synchronized(self) {
        if (instance == nil) {
            instance = [[SinglentonObject alloc] init];
        }
        return instance;
    }
}

-(void) setStock:(NSNumber *)stock{
    // Ensure we are using the shared instance
    if(!array){
        array = [@[] mutableCopy];
    }
    [array addObject:stock];

}

- (NSMutableArray *) getStockArray
{
    return stockArray;
}

在 someMethod 中,您必须将 i 更改为 x:

-(void) write
{
    for(int x=0;x<=1000;x++){
       [[SinglentonObject getInstance] setStock:@x];
    }
}

阅读此内容:

- (void) read
{
    for (NSNumber *currentStock in [[SinglentonObject getInstance] getStockArray]) {
        NSLog(@"%d", [currentStock intValue]);
    }
}

请记住将 getInstance 的每个方法都修改为类方法。我建议您阅读一些 Singlenton 模式文章,例如http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/

于 2013-10-03T16:29:19.787 回答