Lefora Free Forum
Loading
52 views

Crash using block stored in mutable dictionary

Page 1
1–1
rookie - member
1 posts

What can people tell me about why the following program will crash?

#import <Foundation/Foundation.h>

@interface Action : NSObject
+ (void)execute;
@end

@implementation Action
+ (void)execute
{
    NSLog(@"The action was executed.");
}
@end

@interface ActionPerformer : NSObject {
@private
    NSMutableDictionary* _namedActions;
}

+ (ActionPerformer*) performer;
- (void)addAction:(NSString*)action withClass:(Class)class andSelector:(SEL)selector;
- (void)performAction:(NSString*)action;
@end

@implementation ActionPerformer

typedef void(^ActionBlock)();

+ (ActionPerformer*) performer
{
    ActionPerformer* performer = [[ActionPerformer alloc] init];
    performer->_namedActions = [NSMutableDictionary dictionary];
    return performer;
}

- (void)addAction:(NSString *)action withClass:(Class)class andSelector:(SEL)selector
{
    ActionBlock block = ^() { [class performSelector:selector]; };
    // Verify things work
    block();
    [_namedActions setObject:block forKey:action];
}

- (void)performAction:(NSString *)action
{
    ActionBlock block = [_namedActions objectForKey:action];
    // Crash happens here!!!
    block();
}

@end

int main()
{
    @autoreleasepool {
        ActionPerformer* performer = [ActionPerformer performer];
       
        [performer addAction:@"action" withClass:[Action class]
            andSelector:@selector(execute)];
           
        [performer performAction:@"action"];       
    }
    return 0;
}

Page 1
1–1

Locked Topic


You must be a member to post in this forum

Join Now!