NSMutableArray共享实例始终只返回最后一个对象

时间:2013-10-03 16:16:51

标签: ios objective-c for-loop nsmutablearray nsobject

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

1.Shared instance

+ (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?我的代码中有任何错误吗?

1 个答案:

答案 0 :(得分: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中你必须用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的每个方法修改为类方法。我建议您阅读一些类似http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/的Singlenton模式文章。