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.