0

I'm using the following code to set a property that holds information about twitter rate limits in a core data record:

- (Limits *)limits
{
    if (!_limits) {
        [[[TwitterManager sharedManager] API] getRateLimitsForResources:nil successBlock:^(NSDictionary *rateLimits) {
            _limits = [Limits createWithInfo:rateLimits user:_user];
        } errorBlock:^(NSError *error) {
            NSLog(@"Error %s: %@", __PRETTY_FUNCTION__, error);
        }];
    }
    return _limits;
}

When it gets to the last line, it doesn't reflect the new value because the block hasn't finished yet. How can I best go about this?

newacct
  • 119,665
  • 29
  • 163
  • 224
pedroremedios
  • 763
  • 1
  • 11
  • 39

1 Answers1

0

Mixing synchronous and asynchronous code like this is quite hard. The best way to go ahead with this would be to make your limits method asynchronous and have it take an completion block:

- (void)getLimits: (void (^)( Limits *limits ))block
{
      if (_limits) {
         block( _limits );
      } else {
         [[[TwitterManager sharedManager] API] getRateLimitsForResources:nil successBlock:^(NSDictionary *rateLimits) {
            _limits = [Limits createWithInfo:rateLimits user:_user];
            block( _limits );
         } errorBlock:^(NSError *error) {
            NSLog(@"Error %s: %@", __PRETTY_FUNCTION__, error);
            block( nil );
         }];
      }
}

If you want to call your limits method on the main thread you really should go with this option. Blocking the main thread for network access will not lead to great user experience and might get your app killed by the watchdog if the request takes too long.

If this is not an option you basically have to wait for the request to finish. The easiest way to do this would be to use a synchronous method if your TwitterManager supports that. If not there are different ways to handle this, depending on how the TwitterManager class is implemented.

If everything runs on a different thread you could just use a dispatch group to block your current thread until the response arrived (dispatch_group_wait). This will lead to a deadlock if your twitter class tries to dispatch any work on the same queue/thread you send your limits message on.

Sven
  • 22,475
  • 4
  • 52
  • 71