How do I change object's value (passed as a parameter) inside block

梦想的初衷 提交于 2019-12-23 05:42:33

问题


I have an POST request block in one of my functions and I want to change the value of an NSString object inside the block.

I realise that normally one could just prefix the variable __block, but in my case, want to change the value of an NSString object by directly referencing its parameter.

Here's a code skeleton, with relevant comments.

- (void)getItemInformation:(NSString *)inputString{
    //setup stuff
    [manager  POST:@"http://foo.com/iphone_item_string/"
        parameters:parameters
           success:^(AFHTTPRequestOperation *operation, id responseObject) {
               //change inputString directly here
               inputString = (NSString *)responseObject[0];
               //this of course gives an error, but I'm
               //unsure of how to use __block with a parameter
           }
               //foo
           }
     ];
}

And a segment from the calling function

currentEntryData.foo = "lorem";
NSString *retrieveString;
[self getItemInformation:retrieveString];
currentEntryData.bar = retrieveString;
currentEntryData.oof = "ipsum";

回答1:


You can use blocks

- (void)getItemInformationWithCallback:(void(^)(NSString *resultString))callback {

    [manager POST:@"http://foo.com/iphone_item_string/"
        parameters:parameters
           success:^(AFHTTPRequestOperation *operation, id responseObject) {

               // Here you call the callback block
               //
               NSString *newString = (NSString *)responseObject[0];
               if (callback)
                   callback(newString)
           }
     }];
}

And that's how you get the string back

[self getItemInformationWithCallback:^(NSString *resultString) {
    NSLog(@"%@", resultString);
}];


来源:https://stackoverflow.com/questions/21613642/how-do-i-change-objects-value-passed-as-a-parameter-inside-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!