Accessing private variable in Category results in linker error

喜夏-厌秋 提交于 2019-11-30 07:02:53

_displayedItems is a private ivar, so you shouldn't access it, even from a category.

That said, you should try compiling the same code with

gcc -arch i386

and

gcc -arch x86_64

and see the difference. In the 32 bit mode you don't see the error. This shows how fragile the situation is. You really shouldn't.

That said, there's a way to get that ivar by abusing KVC:

@implementation NSCollectionView (displayedItems)

- (NSMutableArray *)myDisplayedItems
{
    return [self valueForKey:@"displayedItems"];
}

@end

Note that you shouldn't name your method just as displayedItems. That would make an infinite loop, because the KVC machinery would find your method earlier than the ivar. See here.

Or you can access any hidden ivar using Objective-C runtime functions. That's also fun.

However, let me say again. There's a big difference in knowing you can do one thing and doing that thing for real. Just think of any hideous crime. and doing that by yourself.

DON'T DO THAT!!!!!

You shouldn't really, but access it like a pointer to a member of a struct:

-(NSMutableArray *)displayedItems {
  return self->_displayedItems;
}

This is a fragile thing to do, as I'm sure you're aware however ;)

UPDATE: Since you've mentioned the above doesn't work, try dropping down to the runtime:

-(NSMutableArray *)displayedItems {
        NSMutableArray *displayedItems;
        object_getInstanceVariable(self, "_displayedItems", (void *)&displayedItems);
        return displayedItems;
}

(Tested, works)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!