Search code examples
objective-cobjective-c-blocks

Objective-C: What does this code mean?


In the MyViewController.h file:

@property (nonatomic, copy, nullable, class) void (^saveMetadataSuccess)(MyViewController*const _Nullable myViewController);

In the MyViewController.m file:

void (^saveMetadataSuccess)(MyViewControllerr* const myViewController) = nil;

+ (void)setSaveMetadataSuccess:(void (^)(MyViewController* const))newMetadataSaveSuccess {
    saveMetadataSuccess = [newMetadataSaveSuccess copy];
}

+ (void (^)(MyViewController* const))saveMetadataSuccess {
    return saveMetadataSuccess;
}

And finally the method which I don't understand:

- (void)success {
dispatch_async(dispatch_get_main_queue(), ^{
        MyViewController.saveMetadataSuccess(self);
    });
}

From my understanding, saveMetadataSuccess is a getter, but MyViewController.saveMetadataSuccess(self);seems to set something.

Can somebody enlighten me?

Thanks


Solution

  • MyViewController.saveMetadataSuccess is a getter and it returns a block that then being called with a param (self).

    So it's like a function that returns other function.

    Also you must not just call MyViewController.saveMetadataSuccess(self); because MyViewController.saveMetadataSuccess is nullable and it will crash if MyViewController.saveMetadataSuccess is null.

    You have to check MyViewController.saveMetadataSuccess first:

    - (void)success {
    dispatch_async(dispatch_get_main_queue(), ^{
            if (MyViewController.saveMetadataSuccess) {
                MyViewController.saveMetadataSuccess(self);
            }
        });
    

    }