3

The block is a property defined in GridScrollView:

typedef BoxView* (^RenderBlock)(NSDictionary* json, CGRect);
@interface GridScrollView : PagingScrollView
@property (nonatomic, copy) RenderBlock renderBlock;

I want to use it like this:

switch(current.tag)
{
    case 1:
        scrollView.renderBlock = ^(NSDictionary* json, CGRect frame)
        {
             //returns a boxview
        }
        break;
     case 2:
        scrollView.renderBlock = ^(NSDictionary* json, CGRect frame)
        {
             //returns a different boxview
        }
        break;
}

While this code works fine the first time around, when it gets reassigned I get an EXC_BAD_ACCESS (code=2, address=0x0) error. What's happening here?

taimur38
  • 33
  • 3

1 Answers1

1

Since the call to the block is itself performing the declaration of an object, try adding an extra pair of braces around it:

case 1: {
            scrollView.renderBlock = ^(NSDictionary* json, CGRect frame) {
             //returns a boxview
            }
        }
        break;

Although I don't know why it would run as is the first time and then crash.

Wienke
  • 3,723
  • 27
  • 40
  • 1
    Why it works: [variables in switch statements](http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement). As Thomas explains, it's a matter of scope. Also see MrZebra's answer, toward the bottom -- I should have said the problem was with the initialization of an object, not with its declaration. – Wienke Aug 25 '12 at 19:43