0

I have singleton where several classes and Threads are updating an NSMutableArray. But when access the NSMutableArray to see the content of the NSMutableArray is empty.

This is part of my code:

@property (strong, nonatomic) NSMutableArray *myArray;

-(NSMutableArray*) myArray{
    if (_ myArray == nil) {
        _myArray = [[NSMutableArray alloc]init];
    }
    return _myArray;
}

-(void)addToArray:(NSString*)myString{
    [self.myArray addObject:myString];
}

Any of you knows why the NSMutableArrays always is empty?

I'll really appreciate your help

user2924482
  • 8,380
  • 23
  • 89
  • 173
  • There is a space between _ and myArray? Is that a typo in your question or your actual code? NSMutableArray is not thread safe. I would suggest you use a serial dispatch queue or @synchronized to protect it from concurrent access. Also you should use a dispatch_once block to allocate your array – Paulw11 Sep 28 '16 at 21:09
  • @Paulw11, yes it was a typo. Can you please post an example of how to use @ synchronized ? – user2924482 Sep 28 '16 at 21:12

1 Answers1

0

It is possible that many classes are reading/writing this array at same time, thus creating bad values. What you need is to synchronise the operations to this array.

Here is a good answer:

Does @synchronized guarantees for thread safety or not?

Community
  • 1
  • 1
prabodhprakash
  • 3,825
  • 24
  • 48