简体   繁体   中英

Objective-C Blocks: Incompatible block pointer types

I'm trying to implement a block call. Here is my method:

- (void) runTest; {
    void (^MyBlock)(id, NSUInteger, BOOL) = ^(id obj, NSUInteger idx, BOOL stop) {
        NSLog(@"Video game %@", (NSString *)obj);
    };

    BOOL stop;
    MyBlock(@"Path of exile", 0, &stop);

    NSArray *videoGames = @[@"fallout", @"Deus ex",@"final fintasy"];

    [videoGames enumerateObjectsUsingBlock:MyBlock];
}

But on this line:

[videoGames enumerateObjectsUsingBlock:MyBlock];

I'm getting this error:

Incompatible block pointer types sending 'void (^__strong)(__strong id, NSUInteger, BOOL)' to parameter of type 'void (^ _Nonnull)(id _Nonnull __strong, NSUInteger, BOOL * _Nonnull)'

Any of you knows what I'm doing wrong or how can I fix this?

I'll really appreciate your help.

the Bool parameter of the Block should be a pointer hence you need to add *

- (void) runTest; {
    void (^MyBlock)(id, NSUInteger, BOOL *) = ^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"Video game %@", (NSString *)obj);
    };

    BOOL stop;
    MyBlock(@"Path of exile", 0, &stop);

    NSArray *videoGames = @[@"fallout", @"Deus ex",@"final fintasy"];
   [videoGames enumerateObjectsUsingBlock:MyBlock];
}

The 3rd parameter of MyBlock should be the pointer of BOOL.

So, add * like below

     void (^MyBlock)(id, NSUInteger, BOOL*) = ^(id obj, NSUInteger idx, BOOL *stop) {
         NSLog(@"Video game %@", (NSString *)obj);
     };

https://developer.apple.com/documentation/foundation/nsarray/1415846-enumerateobjectsusingblock?language=objc

  • (void)enumerateObjectsUsingBlock:(void (^)(ObjectType obj, NSUInteger idx, BOOL *stop))block;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM