Objective-C: Property / instance variable in category

前端 未结 6 1410
清酒与你
清酒与你 2020-11-22 16:56

As I cannot create a synthesized property in a Category in Objective-C, I do not know how to optimize the following code:

@interface MyClass (Variant)
@prope         


        
6条回答
  •  遥遥无期
    2020-11-22 17:38

    Another possible solution, perhaps easier, which doesn't use Associated Objects is to declare a variable in the category implementation file as follows:

    @interface UIAlertView (UIAlertViewAdditions)
    
    - (void)setObject:(id)anObject;
    - (id)object;
    
    @end
    
    
    @implementation UIAlertView (UIAlertViewAdditions)
    
    id _object = nil;
    
    - (id)object
    {
        return _object;
    }
    
    - (void)setObject:(id)anObject
    {
        _object = anObject;
    }
    @end
    

    The downside of this sort of implementation is that the object doesn't function as an instance variable, but rather as a class variable. Also, property attributes can't be assigned(such as used in Associated Objects like OBJC_ASSOCIATION_RETAIN_NONATOMIC)

提交回复
热议问题