Objective-C Category and new iVar

后端 未结 2 1652
长发绾君心
长发绾君心 2020-12-10 05:47

I try to extend the functionality of SimpleAudioEngine of cocos2d with the ability to play several sound effect one after another as some kind of chain. I tried to do this w

相关标签:
2条回答
  • 2020-12-10 06:01

    You can not add iVars but can add property variables. Something like below:

    In your .h:

    #import <objc/runtime.h>
    
    @interface Chair (Liking)
    
         @property (nonatomic, assign)BOOL liked;
     @end
    

    In your .m:

    #import "Chair+ChairCat.h"
    
    @implementation Chair (Liking)
    
     -(BOOL)liked{
    
        return [ objc_getAssociatedObject( self, "_aliked" ) boolValue ] ;    
     }
    
    -(void)setLiked:(BOOL)b{    
        objc_setAssociatedObject(self, "_aliked",  [ NSNumber numberWithBool:b ],OBJC_ASSOCIATION_RETAIN_NONATOMIC ) ;
    
     }
    
    @end
    

    Then somewhere in some other class say myViewController.m

    #import "Chair+ChairCat.h"
    - (void)viewDidLoad {
        /////
        Chair *chair = [[Chair alloc] init];
        [chair setLiked:NO];
    }
    
    0 讨论(0)
  • 2020-12-10 06:17

    You are correct that you can't add instance variables (or synthesized @properties) to a category. You can workaround this limitation using the Objective-C runtime's support for Associative References

    Something like this:

    In your .h:

    @interface SimpleAudioEngine (SoundChainHelper)
        @property (nonatomic, retain) NSMutableArray *soundsInChain;
    @end
    

    In your .m:

    #import <objc/runtime.h>
    static char soundsInChainKey;
    
    @implementation SimpleAudioEngine (SoundChainHelper)
    
    - (NSMutableArray *)soundsInChain
    {
       return objc_getAssociatedObject(self, &soundsInChainKey);
    }
    
    - (void)setSoundsInChain:(NSMutableArray *)array
    {
        objc_setAssociatedObject(self, &soundsInChainKey, array, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    @end
    

    (The standard disclaimer applies. I typed this in the browser, and didn't test it, but I have used this technique before.)

    The documentation I linked to has a lot more information about how associative references work.

    0 讨论(0)
提交回复
热议问题