我试图理解我在互联网上找到的一些代码。我试图调整它,以便我可以在我自己的程序中使用它。在我的程序中,我把它作为单例的实例方法。我理解这是做的大部分,但没有得到“阻止”部分。阻止是什么?在我的实现中,我应该作为参数代替NSSet Photos传递什么。我不明白这一点,我实际上希望从服务器“获取”该位置的照片。那我发送的是什么?
+ (void)photosNearLocation:(CLLocation *)location
block:(void (^)(NSSet *photos, NSError *error))block
{
NSLog(@"photosNearLocation - Photo.m");
NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
[mutableParameters setObject:[NSNumber
numberWithDouble:location.coordinate.latitude] forKey:@"lat"];
[mutableParameters setObject:[NSNumber
numberWithDouble:location.coordinate.longitude] forKey:@"lng"];
[[GeoPhotoAPIClient sharedClient] getPath:@"/photos"
parameters:mutableParameters
success:^(AFHTTPRequestOperation *operation, id JSON)
{
NSMutableSet *mutablePhotos = [NSMutableSet set];
NSLog(@" Json value received is : %@ ",[JSON description]);
for (NSDictionary *attributes in [JSON valueForKeyPath:@"photos"])
{
Photo *photo = [[Photo alloc]
initWithAttributes:attributes];
[mutablePhotos addObject:photo];
}
if (block) {
block([NSSet setWithSet:mutablePhotos], nil);
}
}failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if (block)
{
block(nil, error);
NSLog(@"Error in Photo.m line 145 %@ ", [error description]);
}
}];
}
答案 0 :(得分:2)
无需为照片集传递任何内容。它是块的参数。调用者的工作是传递一个块,当该方法完成一些异步工作时将调用该块。所以你这样称呼它:
// let's setup something in the caller's context to display the result
// and to demonstrate how the block is a closure - it remembers the variables
// in it's scope, even after the calling function is popped from the stack.
UIImageView *myImageView = /* an image view in the current calling context */;
[mySingleton photosNearLocation:^(NSSet *photos, NSError *error) {
// the photo's near location will complete some time later
// it will cause this block to get invoked, presumably passing
// a set of photos, or nil and an error
// the great thing about the block is that it can refer to the caller context
// as follows....
if (photos && [photos count]) {
myImageView.image = [photos anyObject]; // yay. it worked
} else {
NSLog(@"there was an error: %@", error);
}
}];