Frage

i'm confusing about NSMutablearray addobject, i try to make shared instance nsmutable array like this:

1.Shared instance

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

1.1 Method to insert

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

}

1.3 Method to call nsmutablearray

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

2.Method to insert

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

3. Method to call from other controller

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

the log should be show 0-1000 right??? but why its always return 1000......1000 ? is that any wrong in my code?

War es hilfreich?

Lösung

First I'll make a getInstance methods like:

@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;
}

And in someMethod you have to change i by x:

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

For read this:

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

Remember to modify every method of getInstance as class methods.I recommend you that you read some Singlenton pattern article like http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top