0

As you may have experienced, access none-thread safe variables is a big headache. For iOS one simple solution is to use keyword @synchronized, which will add NSLock to insure the data can be accessed by unique one thread, the disadvantage is as below:

  1. Lock too many will reduce app performance greatly, especially when invoked by main thread.

  2. Dead lock will occur when logic becomes complex.

Based on the above considerations, we prefer to use serial queue to handle, each thread safe critical operation will append to the end of the queue, it is a great solution, but the problem is that all access interfaces should by designed in asyn style, see the following one.

-(id)objectForKey:(NSString *)key;

The people who invoke this class aren't reluctant to design in this way. Anyone who has experience on this field please share and discuss together.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
jianhua
  • 1,011
  • 1
  • 12
  • 28
  • So a serial queue doesn't use locks? If not how does it not become corrupt? I don't understand the advantage of using it. – trojanfoe Apr 30 '14 at 09:55
  • A serial queue means you have your own little single-threaded universe inside a bigger multi-threaded universe. You just make sure that the resources that you care about are accessed by tasks in that serial queue, and not by anything else. Just like other things that you must only do on the main thread, which is essentially just another serial queue. – gnasher729 Apr 30 '14 at 10:50
  • But to jianhua, you don't actually have to seem a question? – gnasher729 Apr 30 '14 at 10:51
  • Thanks you guys。 Yes, it is a tough issue, serial queue also can't solve the problem completely, for the basic bottom classes, keep it simple is the key point, make contact with class invokers, try to avoid some use cases. – jianhua May 04 '14 at 03:17

1 Answers1

0

The final solution is using NSUserDefault to store small data, for large cache data put them in file maintained by ourselves.

Per Apple doc the advantage of NSUserDefault is thread safe and will do synchronize work periodically.

jianhua
  • 1,011
  • 1
  • 12
  • 28