I have an NSObject that I create inside a block. As per the code below:
__block NSObject *myObject;
[self myMethod:^{
myObject = [[NSObject alloc] init];
....
}];
if(myObject == nil){
NSLog(@"Why is my object nil?!");
}
In the definition of myMethod I have the following:
backgroundQueue = dispatch_queue_create("backgroundqueue", NULL);
dispatch_async(backgroundQueue,
^{
dispatch_async(dispatch_get_main_queue(),
^{
if(block){
block();//Never called.
}
});
However the block is never called.
The problem here is that you never seem to execute the block in which you instantiate
myObject. For illustration, run this little program:This prints
2012-11-26 05:00:58.519 Untitled 2[23467:707] Your object was createdto the console. The point is that blocks don’t execute themselves. In the code above, although we set the block as an ivar of the class, we don’t execute it until we callsomeMethodon ourFoo.EDIT:
An edit to your question states that the block is not executed in the context of an asynchronous dispatch block sent to the main queue. If this is a command line application, then you must call
dispatch_main()at the end ofmain. See themanpage fordispatch_get_main_queue(). Here is a full working command line application to illustrate this, as well as issues related to race conditions: