0

I am running into a situation where the read and write operations (being done by two different threads and two different view controllers) to an XML file are overlapping.

I tried the following logic to use the same NSLock with the two view controllers :

ViewControllerOne:

(on a background thread using dispatch_async)
- (void)writeToXML {
    // get xmlLock (lock declared globally)
    // write
    // unlock
}

ViewControllerTwo:

(on the main thread)
- (void)readFromXML {
    // get xmlLock (lock referenced from ControllerOne)
    // read
    // unlock
}

However, while debugging, I am noticing that even when ControllerOne has locked the xmlLock, ControllerTwo is still able to get it.

What am I missing here ? Also, is there a better approach for doing something like this ?

Myxtic
  • 5,679
  • 5
  • 48
  • 69
  • where is your lock declared? can you add that code? and where is it assigned and made .. – Daij-Djan Nov 29 '12 at 18:47
  • I have declared myLock in the .h file of ControllerOne, then initialized it in the init method, and then called [myLock lock] from the writeToXML method. – Myxtic Nov 29 '12 at 19:03

1 Answers1

1

Are you positive it's the same NSLock instance? Regardless, it seems like a better way might be to have a dispatch queue for that; readFromXML can dispatch_sync onto it, and writeToXML can dispatch_async onto it.

Catfish_Man
  • 41,261
  • 11
  • 67
  • 84
  • To use the same dispatch queue from the two view controllers, is there a way to get a queue by it's label ? (I didn't find one) Or should I just declare the queue as an ivar for one controller and access it that way ? – Myxtic Nov 29 '12 at 19:18
  • The latter. There's no global name->queue mapping table. – Catfish_Man Nov 29 '12 at 19:23
  • 1
    (Or make a static one with a function that lazily initializes it and returns the static instance) – Catfish_Man Nov 29 '12 at 19:24
  • Can you please elaborate a little on how I can do this ? (Or make a static one with a function that lazily initializes it and returns the static instance) – Myxtic Nov 29 '12 at 20:18
  • dispatch_queue_t sharedQueue() { static dispatch_queue_t instance; static dispatch_once_t once; dispatch_once(&once, ^{ instance = dispatch_queue_create("label", 0); }); return instance; } – Catfish_Man Nov 29 '12 at 20:55