0

我试图理解我在互联网上找到的一些代码。我试图调整它,以便我可以在我自己的程序中使用它。在我的程序中,我将此作为单例的实例方法。我了解大部分这是在做什么,但没有得到“块”部分。块是干什么用的?在我的实现中,我应该传递什么作为参数来代替 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]);
       }
      }];
      }
4

1 回答 1

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);
    }
}];
于 2012-10-19T04:44:32.160 回答