Avoid copying NSMutableArray for reading with multithreaded writes

前端 未结 3 1297
囚心锁ツ
囚心锁ツ 2020-12-19 12:04

I have a class that uses a mutable array that is modified once after a lot of reads (new items arrive).

The problem is that when times comes to mutate the array, rea

3条回答
  •  囚心锁ツ
    2020-12-19 12:30

    The simplest approach is to use @synchronized, like this:

    -(void) accessTheArray {
        MyClass *obj;
        @synchronized(theArray) {
            obj = [theArray objectAtIndex:...];
        }
        [obj someMessage];
    }
    

    EDIT: If not using ARC, you might want to retain/autorelease the object, otherwise it might be removed from the array (and released) before someMessage is called (thanks for omz for this excellent comment).

提交回复
热议问题