Home > Software engineering >  Capturing data in NSURLSession
Capturing data in NSURLSession

Time:08-13

Let's say I want to access a variable called key that comes from outside the NSURLSession in my callback function (see code bellow). The problem is that key seems to get deleted right when I enter the session. Is there a way to capture the key variable (like with c lambdas) so I have access to it inside the session?

bool FacadeIOS::uploadRequest(const std::string& key,
                              InterfaceCallbackHTTP* callback){
    // ...setup the request
 
    // key is not yet deleted, still had correct value
    LOG("key before session: {}", key);

    [[[NSURLSession sharedSession] dataTaskWithRequest:request
                                     completionHandler:
        ^(NSData * _Nullable data,
        NSURLResponse * _Nullable response,
        NSError * _Nullable error) {

        // key = ""
        LOG("key after session: {}", key);

        // Send to callback
        if(callback != nullptr)
            // The callback will be called with the wrong key value = ""
            callback->didUploadFile(key);
    }] resume];

CodePudding user response:

You're passing a reference to a string. But you need the string to live longer than the function call. So you need a copy of the string, not a reference to it. Remove the & in the signature.

Alternately, you could make an explicit copy:

std::string key = key;  // Make a new copy that shadows the reference.
  • Related