why does this code give EXC_BAD_ACCESS (using IMP)

后端 未结 2 1497
温柔的废话
温柔的废话 2021-02-03 13:44

This code gives me EXC_BAD_ACCESS, why?

NSMutableDictionary  *d = [[NSMutableDictionary alloc] init];
IMP imp= [d methodForSelector:@selector(setObject:forKey:)          


        
2条回答
  •  [愿得一人]
    2021-02-03 14:23

    The problem is that IMP has a return type of "id" which ARC will attempt to manage. You need to cast your function pointer to have a return type of void (consistent with the method you are calling):

        NSMutableDictionary  *d = [[NSMutableDictionary alloc] init];
        IMP imp= [d methodForSelector: @selector(setObject:forKey:)];
        void (*func)(__strong id,SEL,...) = (void (*)(__strong id, SEL, ...))imp;
        func( d,  @selector(setObject:forKey:), @"obj", @"key" );
    

提交回复
热议问题