问题
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