2016-04-25 17 views
3

當我用nil調用這個方法時,應用程序崩潰了,但我想知道如何用空值來編寫它。如何使用空值來編寫完成塊?

CRASH

[KPTaxnoteApiSaveHandler saveEntryWithUuid:uuid completion:nil]; 

OK

[KPTaxnoteApiSaveHandler saveEntryWithUuid:uuid completion:^(NSError *error) {}]; 

這是代碼。

+ (void)saveEntryWithUuid:(NSString *)uuid completion:(void (^ __nullable)(NSError * _Nullable error))completion { 

    NSLog(@"saveEntryWithUuid"); 

    Entry *entry = [Entry MR_findFirstByAttribute:@"uuid" withValue:uuid]; 

    NSDictionary *params = @{@"entry[uuid]":entry.uuid}; 

    [KPTaxnoteApiSaveHandler postWithUrl:kApiUrlStringForEntry params:params completion:^(NSError *error) { 

     if (!error) { 

      [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) { 

       Entry *entry = [Entry MR_findFirstByAttribute:@"uuid" withValue:uuid inContext:localContext]; 
       entry.needSave = @NO; 
      }]; 
     } 

     completion(error); 
    }]; 

+ (void)postWithUrl:(NSString *)urlStr params:(NSDictionary *)params completion:(nullable void (^)(NSError *_Nullable error))completion { 

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 

    [manager POST:urlStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { 

     completion(nil); 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

     completion(error); 
    }]; 

回答

7

崩潰發生在哪裏?我的第一個猜測是你需要這樣做:

if (completion) { 
    completion(nil); // Or completion(error); 
} 

這將處理完成爲零的情況。

+0

是的,永遠不要試圖取消引用'nil'塊指針。 – rmaddy

+0

解決了!非常感謝你! –