2012-10-19 60 views
0

我試圖瞭解我在互聯網上找到的一些代碼。我試圖調整它,所以我可以在我自己的程序中使用它。在我的程序中,我將它作爲一個單例的實例方法。我理解這是做什麼的大部分,但沒有得到「塊」的一部分。什麼是塊?在我的實施中,我應該通過什麼來代替NSSet Photos。我不明白這一點,因爲Im實際上希望能夠從服務器上「獲取」該位置的照片。那麼,我發送了什麼?iOS - AFNetworking - 理解這段代碼 - 它做什麼?

+ (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]); 
     } 
     }]; 
     } 

回答

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); 
    } 
}]; 
+0

感謝您的迴應。我還有一個問題,原始函數中是否有代碼來處理返回呼叫的成功和失敗?如果那是正確的,那麼我是否需要在調用方法中的函數外部添加代碼,以處理該塊?這是令我困惑的。誰處理該塊,來電者或單身人士? – banditKing

+0

看起來成功後,該方法將結果傳遞給塊。失敗時,它會記錄錯誤並用nil和錯誤調用塊。如果這就是你所需要做的,那麼你可以傳遞一個空塊 - 這就像一個空方法(NSSet * set,NSError * error)^ {}。但是大概你會這樣稱呼它,因爲你想對這些圖像做些什麼,比如保存它們或者將它們(或者錯誤)呈現給用戶。這就是你在這個區塊裏所做的。 – danh

+0

感謝它的工作! +1的幫助 – banditKing