我想为两个字符串赋值,然后在 block 外使用它们,或者作为另一个类中的属性使用。但我得到 Null 作为返回。
这是代码:
__block NSString* citySTR = nil;
__block NSString* countrySTR = nil;
[geocoder reverseGeocodeLocation:locationManager.location completionHandler:
^(NSArray* placemarks, NSError* error){
if ([placemarks count] > 0)
{
citySTR = [[placemarks objectAtIndex:0] administrativeArea];
countrySTR = [[placemarks objectAtIndex:0] country];
}
}];
当我 NSLog
citySTR 和 countrySTR 在 block 外时,我得到 Null
。
最佳答案
之后你想用这些值做什么? 如果你想设置标签或调用其他类方法,你可以在 block 内进行。 另一种解决方案是进行委托(delegate)/添加观察者:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"notificationName" object:nil]; - this one suppose to listen do the event (called at the initialisation)
这个调用它的:
[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:obj];
您可以将 citySTR 和 countrySTR 作为属性 - 也许这会有所帮助
关于ios - 如何访问已在 block 内分配的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24244608/