1

I have used blocks a few times but never with declaring a typedef first.

I am trying to setup this definitions on a class (lets call it ClassA)

typedef void (^myBlock)();

@property (nonatomic, copy) myBlock onCompletion;

Then I create an instance of the object this class represents and do this:

ClassA *obj = [[ClassA alloc] init];
obj.onCompletion = ^(){
   // my code here
};

it is complaining "incompatible block pointer types assigning"...

can you guys explain?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Duck
  • 34,902
  • 47
  • 248
  • 470

4 Answers4

1

Although you don't have to specify the return type of a block, you must specify void if your block doesn't take any parameters.

limon
  • 3,222
  • 5
  • 35
  • 52
1

Check out this link for block reference: block syntax

Just guessing it might be because you left the block parameter type blank.

typedef void (^myBlock)(void); //Untested
Eric
  • 5,671
  • 5
  • 31
  • 42
0

The only difference in the declared block type myBlock and the type of the block literal might be the return type.

If you leave the return type out in a block literal the compiler figures it out automatically:

myBlock block1 = ^() { // everything is fine
   return;
};

myBlock block2 = ^() { // does not work, types differ
   return 1;
};
Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
0

At the request of the OP I am posting my original comment as an answer even though there are other answers stating the same thing:

You need to clearly specify that the block takes no parameters. Your typedef should be:

typedef void (^myBlock)(void);
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I thought that by leaving it blank it would be void, but I was wrong. Thanks. – Duck Feb 19 '14 at 19:01
  • I'm not sure but I think when you declare a block or function with empty parentheses (instead of an explicit `void`), the compiler assumes a single `int` parameter. – rmaddy Feb 19 '14 at 19:03
  • @DesperateDeveloper Are you sure this is the full answer to the problem. For me the code you posted works fine, as long as the block does not return a thing. – Nikolai Ruhe Feb 19 '14 at 19:04
  • 1
    @rmaddy The C standard says that a function with no explicit parameters takes an unspecified number of parameters. They will just not be checked by the compiler. – Nikolai Ruhe Feb 19 '14 at 19:09
  • @NikolaiRuhe I knew I fuzzy on that detail. Either way it is different from no parameters. – rmaddy Feb 19 '14 at 19:10
  • @rmaddy Yes. I'm feeling a bit uncomfortable with this solution because I can't reproduce the problem like this. Only the one I pointed out. – Nikolai Ruhe Feb 19 '14 at 19:12