11

I know about the possibility of declaring private properties on a class by putting them inside an unnamed category on that class declared in the implementation (.m) file of that class. That's not what I want to do.

I'm dealing with a named category on a class that adds some functionality to that class. For this functionality, it would help me very much to have a private property to use in my category - so the usual way of achieving this (described above) doesn't seem to work for me. Or does it? Please enlighten me!

Marco
  • 6,692
  • 2
  • 27
  • 38
Jan Z.
  • 6,883
  • 4
  • 23
  • 27

1 Answers1

24

Inside your category's implementation file, declare another category and call it something like MyCategoryName_Private, and declare your private properties there. Provide implementations of the -propertyName and -setPropertyName: methods using associated objects.

For example, your implementation file might look like this:

#import "SomeClass+MyCategory.h"
#import <objc/runtime.h>

@interface SomeClass (MyCategory_Private)

@property (nonatomic, strong) id somePrivateProperty;

@end

@implementation SomeClass (MyCategory_Private)

static void *AssociationKey;

- (id)somePrivateProperty 
{
    return objc_getAssociatedObject(self, AssociationKey);
}

- (void)setSomePrivateProperty:(id)arg
{
    objc_setAssociatedObject(self, AssociationKey, arg, OBJC_ASSOCIATION_RETAIN);
}

@end

@implementation SomeClass (MyCategory)

// implement your publicly declared category methods

@end
Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
  • 1
    Yahey, thank you very much! That is exactly what I've been looking for! Maybe some people would consider this to be not the best coding practice, putting a category entirely into an ´.m´ file, but anyway this solves my problem and makes stuff much easier for me :) – Jan Z. Jan 22 '13 at 14:00
  • 1
    Beautiful. Thank you! – theDuncs Sep 15 '16 at 10:15
  • I think I should create more AssociationKeys if I want to have more private properties? – allenlinli Jan 20 '17 at 04:17