Simon Edström
Simon Edström

Reputation: 6619

Locking with Obj-C

I'm really getting confused how locking works in Obj-C.

I simply have a network request which I only want to call once at the same time. I want to block all other calls to it until it has received some data.

My lock is of type NSCondition and static, _sending is just a bool. This is my implementation. The getWithSuccess is using AFNetworking for perform some action network requests, so I think it can start multiple threads or using some magic in GDC.

My problem is that this implementation just give me deadlocks, and I need some hint how a correct implementation should work.

[lock lock];

while (_sending)
    [lock wait];

_sending = YES;

[self getWithSuccess:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    _sending = NO;

    [lock signal];
    [lock unlock];


} fail:^() {
    _sending = NO;

    [lock signal];
    [lock unlock];
}];

Upvotes: 1

Views: 192

Answers (1)

Lance
Lance

Reputation: 9012

I've accomplished something similar to this using NSOperation and NSOperationQueue. Depending on your needs, you can subclass NSOperation and check if an operation of that type is in the queue before adding a new one (to prevent duplicate calls) or just put your network requests in the queue and they will execute in order, one at a time by setting maxConcurrentOperationCount to 1

You mentioned you are using AFNetworking which has an NSOperation subclass called AFURLConnectionOperation that might suit your needs as well.

Upvotes: 1

Related Questions