0

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.

user2924482
  • 8,380
  • 23
  • 89
  • 173
  • Side note, if you know that the object will be a always a `NSString`, you can replace `^(id obj` with `^(NSString * obj` avoiding the next casting `(NSString *)obj`. – Larme May 29 '20 at 08:00

2 Answers2

2

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];
}
dRAGONAIR
  • 1,181
  • 6
  • 8
1

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;
pompopo
  • 929
  • 5
  • 10