2012-11-29 26 views
2

我有一個單例類,需要一個成功和失敗塊作爲參數的方法,它調用異步執行的另一種方法,並且也使用成功和失敗塊。我的方法的成功塊由異步方法的成功塊調用。一切都很好,除非我的視圖控制器在成功塊返回之前被釋放,在這種情況下,應用程序崩潰。的iOS塊異步回調 - 視圖 - 控制器後,曹景偉崩潰被釋放

這種情況似乎類似於在dealloc方法中將委託設置爲nil。我應該如何處理這個塊?

這裏是我的代碼如下所示:

- (void)getObjectsWithId:(NSInteger)id success:(void (^)(NSArray *objects))success failure:(void (^)(NSInteger statusCode, NSError *error))failure { 

    NSString *path = [NSString stringWithFormat:@"/my_objects/%d/objects", id]; 

    [self getPath:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { 
     NSMutableArray *objects = [[NSMutableArray alloc] initWithCapacity:[responseObject count]]; 

     for (NSDictionary *dict in responseObject) { 
      Object *object = [[Object alloc] initWithDictionary:dict]; 
      [objects addObject:object]; 
     } 

     success(objects); 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     failure(operation.response.statusCode, error); 
    }]; 
} 
+1

是否使用ARC? –

+0

你需要證明你的'的getPath代碼:參數:成功:失敗:'方法 – newacct

+0

我使用ARC的的getPath:參數:成功:失敗:方法是AFNetworking的一部分。 –

回答

0

您可以使用通知中心,聽取當視圖被釋放並設置塊零,所以它不會試圖返回任何東西..

張貼視圖獲取dealloced權利之前通知:

[[NSNotificationCenter defaultCenter] 
postNotificationName:@"myNotificationName" 
object:broadcasterObject]; 

並註冊一個事件:

[[NSNotificationCenter defaultCenter] 
addObserver:listenerObject 
selector:@selector(receivingMethodOnListener:) 
name:@"myNotificationName" 
object:nil];