I have my main application delegate which contains a method that returns an object. This application delegate runs on the main thread.
I also have a NSOperation that gets run on a different thread. As well as wanting to be able to call my app delegate method on my main thread sometimes, I also need to call it from my NSOperation thread to get the object that it returns. My first question is, if I call this from my other thread...
id newObject = [[[UIApplication sharedApplication] delegate] myMethod];
... will that method be processed on the same thread as the NSOperation, or will it be the same thread (main) as the application delegate is on?
I also want to make sure that the code within myMethod
is only called once at a time by either my operation thread or my main thread. Can I just create a NSLock instance var in my application delegate and do something like:
-(id)myMethod {
[myLock lock];
myObject = // Get or create my object to return
[myLock unlock];
return myObject;
}
Thanks for your help!
Mike
Unless you explicitly write code to cause something to execute on another thread, every method call is going to be executed directly on the thread it was called upon. There is no magic with a method call. You can think of it as having the exact same semantics/ABI as a C function call for the purposes of threading.
Your locking pattern will work fine to ensure exclusive access across threads.
Two additional unrelated notes (because so many people trip over it):
declaring a property as
atomic
has little to do with thread safety. Atomicity only guarantees that you get a valid value, not the correct value (there is a difference).autoreleased objects are never safe to pass between threads. You need an explicit
retain
on the sending thread and a balancing eventualrelease
on the receiving thread.