1

In Objective-C blocks can be run asynchronously or synchronously, depending on the purpose. Just looking at an API method won't tell us which way will happen.

It would be nice if there was a convention that indicates whether a block is going to be dispatched to another thread or run in synch with the current thread.

Is there one?

Update: Other languages might use annotations. I'm thinking something along the lines of the NS_REQUIRES_NIL_TERMINATION that is used in va_args methods.

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • assuming you are referring to GCD, you should know difference between `dispatch_sync` and `dispatch_async` – Bryan Chen Aug 07 '13 at 03:00
  • 1
    I'm talking about eg [databaseQueue inDatabase:^(FMDatabase* database){}] vs [assetLibrary enumerateUsingBlock]. . . the latter is asynch while the former is not. And they may or may not use GCD, which doesn't matter to at this point, as an API consumer. . . seems like there is no convention here, and one would be helpful. – Jasper Blues Aug 07 '13 at 03:07
  • then is nothing to do with block, it is all about how API designed to work. – Bryan Chen Aug 07 '13 at 03:20
  • I mean if a parameter accepts a block, it is ambiguous whether the block will be run on the current thread or another. . . I suggest a convention of some sort would help communicate an API's intention, with minimal effort from both the author and users. (This would help to eliminate the time waste of going to another source for the info). – Jasper Blues Aug 07 '13 at 03:30
  • @KhanhNguyen, unfortunately the information is often not there. Also, not being in a standard format in addition to have to link through to it, requires greater time investment. This equals waste, which ultimately leads to a higher cost to the end user. . . – Jasper Blues Aug 07 '13 at 03:46
  • Well, I would come back and ask you, why do you care whether it's synchronous or asynchronous? – newacct Aug 07 '13 at 23:29

1 Answers1

1

NO. There are no standard way to define how the block get executed. You have to read documentation (if any) or source code (if available) to find out.

However, you have control the block you pass in so you can make it always executed on main thread or asynchronously.

e.g.

[queue performBlock:^ {
    dispatch_async(dispatch_get_main_queue(), ^{
        // you know code here must be on main thread
    });
}];
Bryan Chen
  • 45,816
  • 18
  • 112
  • 143