Accessing private variable in Category results in linker error

后端 未结 2 1440
半阙折子戏
半阙折子戏 2020-12-30 09:51

EDIT: I\'m not going to do this, I now realize how dangerous this can be. But, the question stays for purely academic purposes.

I\'m trying to implement a category o

2条回答
  •  囚心锁ツ
    2020-12-30 10:11

    _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!!!!!

提交回复
热议问题