How do I keep an object in scope, which performs a task in background, that was instantiated from a method of another object?
See the following example. The display method of object A instantiates object B and calls its display method. When the B object’s display method, starts an asynchronous task, control goes back to A::display method, which returns, and bObject gets deallocated. When bObject’s data/method are accessed in the background thread, this will throw exception.
What is the best way of maintaining the scope for object B? I can declare the object B as a member variable for A, but this will increase the scope for the entire lifespan of object A.
@implementation A
-(void) display
{
B* bObject = [[B alloc] init];
[bObject display];
}
@end
@implementation B
-(void) display
{
dispatch_async((dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0),{
self.data = 5;
---------
});
@end
Previously in iOS you would be able to do this and then assuming your object created returned with some delegate callback you could release it. Now you will have to make “bObject” a member variable for your class and either set it to nil when you are done with it or wait for A to be destroyed which will put bObject out of scope. I’m assuming this is with ARC and as soon as “display” finishes your local variable is out of scope and is deallocated because of ARC.
you can add this to A: