如何在块内更改对象的值(作为参数传递) [英] How do I change object's value (passed as a parameter) inside block
本文介绍了如何在块内更改对象的值(作为参数传递)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的一个函数中有一个 POST 请求块,我想更改块内 NSString 对象的值.
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.
我意识到通常可以只给变量 __block
加上前缀,但在我的例子中,想通过直接引用它的参数来更改 NSString 对象的值.
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";
推荐答案
可以使用块
- (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);
}];
这篇关于如何在块内更改对象的值(作为参数传递)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文