Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write completion block with nullable?

When I call this method with nil, the app crashes, but I want to know how to write it with nullable.

CRASH

 [KPTaxnoteApiSaveHandler saveEntryWithUuid:uuid completion:nil];

OK

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

This is the code.

+ (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);
    }];
like image 863
Non Umemoto Avatar asked Jan 07 '23 04:01

Non Umemoto


1 Answers

Where is the crash happening? My first guess is you need to do something like this:

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

This will handle the case where the completion is nil.

like image 98
Mark Avatar answered Jan 15 '23 13:01

Mark