Canceling a Connection


The book mentions that you can use the sharedConnectionList in BNRConnection.m to cancel a request. How would I go about canceling a request when navigating away from the View (Controller) that made initiated the request?


Well, it depends on how you want to initiate the connection being stopped. Let’s say leaving a view controller that you initiated the request in cancels it. I think (and there are so many ways to pull this off) the best approach would be to generate a unique string each time a BNRConnection was began. Change the BNRConnectionList to an NSMutableDictionary. Store the connection for that unique string in the dictionary. Have the store return the key from the fetch method, the view controller will hang onto it. When the view controller wants to cancel it, it sends a message to the store asking it it cancelForKey, passing that key along, the store looks up the connection object in the dictionary for that key and sends it a cancel message.


Thanks for the quick response. I do have one more question. How do I pull out the connection from the static sharedConnectionList in StoreConnection?

Big ol’ edit: I’ve worked out some code but I want to make sure I’m doing this correctly:

In my Store.m:

- (void)stopRequestByConnectionID:(NSString *)id
    StoreConnection *connection = [StoreConnection getConnectionInstanceByID:id];

    if (connection)
        [connection stop];

And in my StoreConnection.m:

+ (StoreConnection *)getConnectionInstanceByID:(NSString *)id
    if (sharedConnectionList)
        // Return a StoreConnection object where the Connection ID matches
        return nil;

- (void)stop
    // I'll do some other clean up/notification here
    [internalConnection cancel];

How does that look?


This looks great. Now you have to figure out who gets the ID and who handles the canceling. I’d suggest that the controller has limited knowledge of connections, but enough knowledge to identify the connection to the store who does the actual canceling.


What I did is create a unique NSString using

self.connectionID = [[NSUUID UUID] UUIDString];
in the init method of BNRConnection. Once the connection has been created, the store stores that same string for reference.

When a cancel request comes from user, the controller tells the store to cancel the current connection, and the store passes it on to the connection using stopRequestByConnectionID:.