PropertyKit provides tools for working with Objective-C Declared Properties
Objective-C
Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
Tests
.gitignore
PropertyKit.h
PropertyKit.mm
PropertyKitTests.h
PropertyKitTests.m
README.md

README.md

PropertyKit for Objective-C

PropertyKit provides tools for working with Objective-C Declared Properties.

Copyright © 2011, Jon Parise.

Installation

Simply include these source files in your project:

  • PropertyKit.h
  • PropertyKit.mm

The repository also includes a SenTestingKit-compatible unit test:

  • PropertyKitTests.h
  • PropertyKitTests.m

Usage

Introspection

Objective-C properties have a name and a set of attributes. The Objective-C runtime represents these attributes as a property type string. Accessing individual attributes involves parsing this custom string format. PropertyKit handles this parsing for you and provides two convenient ways to access property attributes.

The C API wraps the low-level parser:

objc_property_t property = class_getProperty([UIDevice class], "name");
PKPropertyAttributes attributes = PKPropertyAttributesMake(property);
NSLog(@"Property %s is %s", property_getName(property), attributes.isReadOnly ? "readonly" : "readwrite");

And the higher-level PKProperty class provides more convenient access:

PKProperty *property = [PKProperty propertyWithName:@"name" forClass:[UIDevice class]];
NSLog(@"Property %@ is %@", property.name, property.isReadOnly ? @"readonly" : @"readwrite");

Observing

PropertyKit provides a mechanism for observing changes to property values. This is similar to Key-Value Observing but trades features for speed. It works by replacing synthesized property setters with custom implementations that call an object-level notification selector when a property is changed.

Objects can only observe their own properties; objects cannot directly observe the properties of other objects.

Observed properties need to be registered:

+ (void)initialize
{
    [self addObservedProperty:@"hidden"];
}

The object will then be notified of changes to observed properties:

- (void)observeValueForProperty:(NSString *)name value:(id)value
{
    NSLog(@"Property %@ has a new value: %@", name, value);
}

Future Ideas

Observing

  • Consider sending both the old and new values to the observer.
  • Support structs (e.g. CGRect). This will require wrapping the new value in an NSValue box so that it could be passed back to the observer.
  • Support atomic (synchronized) setter operations.
  • Emit KVO notifications from our custom setter implementations.
  • Offer the option of using method swizzling to call the original setter instead of completely replacing the setter implementation. This will provide greater end-user flexibility at the expense of some speed.