Skip to content

Instantly share code, notes, and snippets.

@ngabel
Created May 3, 2011 19:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ngabel/954035 to your computer and use it in GitHub Desktop.
Save ngabel/954035 to your computer and use it in GitHub Desktop.
A custom class that lets you use property accessor syntax to set/get member vars. (Works very much like NSManagedObject)
If you use this code it would be great to receive a credit and link back in your app! Thanks.
-Niels Gabel
PlacePop Inc
http://placepop.com
http://nielsbot.com
Copyright (c) 2010 PlacePop Inc
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
//
// PropertyContainer.h
// PlacePop
//
// Created by Niels Gabel on 8/6/10.
// Copyright (c) 2010 PlacePop Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface PropertyContainer : NSObject <NSCoding>
{
}
// may not exist--used for primitive set/get in default case
@property ( nonatomic, readonly ) NSMutableDictionary * properties ;
-(NSDictionary*)dictionaryRepresentation ;
// for subclassers:
-(void)setPrimitiveValue:(id)value forKey:(NSString*)key ;
-(id)primitiveValueForKey:(NSString*)key ;
@end
//
// PropertyContainer.m
// PlacePop
//
// Created by Niels Gabel on 8/6/10.
// Copyright (c) 2010 PlacePop Inc. All rights reserved.
//
#import "PropertyContainer.h"
#import <objc/runtime.h>
#define ReleaseAndZero(__var) { [ (id)(__var) release ] ; __var = nil ; }
static CFMutableDictionaryRef classesToMethodDictionaries = NULL ;
inline NSString * LookupKey( Class theClass, SEL selector ) ;
static void Setter(id self, SEL selector, id value)
{
NSString * key = LookupKey( [ self class ], selector ) ;
if ( !key || key == (id)kCFNull )
{
[ self setValue:value forUndefinedKey:key ] ;
}
[ self setValue:value forKey:key ] ;
}
static void Setter_BOOL(id self, SEL selector, BOOL value)
{
Setter( self, selector, [ NSNumber numberWithBool:value ] ) ;
}
static void Setter_Float( id self, SEL selector, float value )
{
Setter( self, selector, [ NSNumber numberWithFloat:value ] ) ;
}
static void Setter_UInteger( id self, SEL selector, NSUInteger value )
{
Setter( self, selector, [ NSNumber numberWithUnsignedInteger:value ] ) ;
}
static id Getter(id self, SEL selector)
{
NSString * key = LookupKey( [ self class ], selector ) ;
if ( !key || key == (id)kCFNull )
{
return [ self valueForUndefinedKey:key ] ;
}
return [ self valueForKey:key ] ;
}
static BOOL Getter_BOOL(id self, SEL selector)
{
return [ Getter( self, selector ) boolValue ] ;
}
static float Getter_Float( id self, SEL selector )
{
return [ Getter( self, selector ) floatValue ] ;
}
static NSUInteger Getter_UInteger( id self, SEL selector )
{
return [ Getter( self, selector ) unsignedIntegerValue ] ;
}
#pragma mark - NSString (PropertyContainer)
@interface NSString (PropertyContainer)
-(NSString*)uppercaseFirstLetter ;
-(NSString*)lowercaseFirstLetter ;
@end
#pragma mark - PropertyContainer
@implementation PropertyContainer
@synthesize properties = _properties ;
+(void)load
{
classesToMethodDictionaries = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, NULL, & kCFTypeDictionaryValueCallBacks ) ;
}
+ (BOOL)resolveInstanceMethod:(SEL)aSelector
{
if ( [ [ self superclass ] resolveInstanceMethod:aSelector ] )
{
return YES ;
}
CFMutableDictionaryRef selectorsToKeys = (CFMutableDictionaryRef)CFDictionaryGetValue( classesToMethodDictionaries, self ) ;
if ( !selectorsToKeys )
{
selectorsToKeys = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, NULL, & kCFTypeDictionaryValueCallBacks ) ;
CFDictionarySetValue( classesToMethodDictionaries, self, selectorsToKeys ) ;
CFRelease( selectorsToKeys ) ;
}
NSString * selectorString = NSStringFromSelector( aSelector ) ;
NSString * propertyName = nil ;
BOOL isSetter = NO ;
BOOL isToMany = NO ;
if ( [ selectorString hasPrefix:@"set" ] && [ selectorString hasSuffix:@":" ] )
{
propertyName = [ [ selectorString substringWithRange:(NSRange){ 3, selectorString.length - 3 - 1 } ] lowercaseFirstLetter ] ;
isSetter = YES ;
}
// else if ( [ selectorString hasPrefix:@"numberOf" ] )
// {
// propertyName = [ [ selectorString substringFromIndex:8 ] lowercaseFirstLetter ] ;
// isToMany = YES ;
// }
else
{
propertyName = selectorString ;
}
objc_property_t prop = class_getProperty( self, [ propertyName UTF8String ] ) ;
if ( !prop || isToMany )
{
CFDictionarySetValue( selectorsToKeys, aSelector, kCFNull ) ;
return NO ;
}
CFDictionarySetValue( selectorsToKeys, aSelector, propertyName ) ;
char * attributesString = strdup( property_getAttributes( prop ) ) ;
{
char * tempString = attributesString ;
strsep( &tempString, "," ) ; // delimit on ',', don't iterate strsep since we just want the first string
}
BOOL ok = NO ;
{
const char * supportedTypeEncodings[] = { @encode( BOOL ), @encode( float ), @encode( NSUInteger ) } ;
const IMP kSetters[] = { (IMP)Setter_BOOL, (IMP)Setter_Float, (IMP)Setter_UInteger } ;
const IMP kGetters[] = { (IMP)Getter_BOOL, (IMP)Getter_Float, (IMP)Getter_UInteger } ;
char * typeString = attributesString + 1 ; // skip over initial 'T'
BOOL added = NO ;
for( int index=0, count = sizeof( supportedTypeEncodings ) / sizeof( supportedTypeEncodings[0] ); index < count; ++index )
{
if ( strcmp( typeString, supportedTypeEncodings[ index ] ) == 0 )
{
if ( isSetter )
{
NSString * typeSignature = [ NSString stringWithFormat:@"v@:%s", supportedTypeEncodings[ index ] ] ;
ok = class_addMethod( self, aSelector, kSetters[ index ], [ typeSignature UTF8String ] ) ;
}
else
{
NSString * typeSignature = [ NSString stringWithFormat:@"%s@:", @encode( BOOL ) ] ;
ok = class_addMethod( self, aSelector, kGetters[ index ], [ typeSignature UTF8String ] ) ;
}
added = YES ;
break ;
}
}
// default case, we assume type is 'id'
if ( !added )
{
if ( isSetter )
{
ok = class_addMethod( self, aSelector, (IMP)Setter, "v@:@" ) ;
}
else
{
ok = class_addMethod( self, aSelector, (IMP)Getter, "@v:" ) ;
}
}
}
free( attributesString ) ;
return ok ;
}
- (void)dealloc
{
ReleaseAndZero( _properties ) ;
[super dealloc];
}
-(void)encodeWithCoder:(NSKeyedArchiver*)encoder
{
[ encoder encodeObject:_properties forKey:@"properties" ] ;
}
-(id)initWithCoder:(NSKeyedUnarchiver*)decoder
{
if (( self = [ super init ] ))
{
_properties = [ [ decoder decodeObjectForKey:@"properties" ] retain ] ;
}
return self ;
}
-(NSMutableDictionary*)properties
{
if ( !_properties )
{
_properties = [[ NSMutableDictionary alloc ] init ] ;
}
return _properties ;
}
-(NSString*)description
{
return [ NSString stringWithFormat:@"%@<%p>={%@}", [ self class ], self, self.properties ] ;
}
-(id)valueForKey:(NSString*)key
{
if ( LookupKey( [ self class ], NSSelectorFromString( key ) ) )
{
return [ self primitiveValueForKey:key ] ;
}
return [ super valueForKey:key ] ;
}
-(void)setValue:(id)value forKey:(NSString*)key
{
if ( LookupKey( [ self class ], NSSelectorFromString( [ NSString stringWithFormat:@"set%@:", [ key uppercaseFirstLetter ] ] ) ))
{
[ self willChangeValueForKey:key ] ;
[ self setPrimitiveValue:value forKey:key ] ;
[ self didChangeValueForKey:key ] ;
}
else
{
[ super setValue:value forKey:key ] ;
}
}
-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
}
-(id)valueForUndefinedKey:(NSString*)key
{
return nil ;
}
-(void)setPrimitiveValue:(id)value forKey:(NSString*)key
{
[ self.properties setValue:value forKey:key ] ;
}
-(id)primitiveValueForKey:(NSString*)key
{
return [ self.properties valueForKey:key ] ;
}
-(NSDictionary*)dictionaryRepresentation
{
return [ self.properties copy ] ;
}
@end
#pragma mark -
NSString * LookupKey( Class aClass, SEL selector )
{
CFDictionaryRef dict = CFDictionaryGetValue( classesToMethodDictionaries, aClass ) ;
NSString * key = dict ? (id)CFDictionaryGetValue( dict, selector ) : nil ;
if ( !key )
{
Class theClass = [ aClass superclass ] ;
while( theClass )
{
dict = CFDictionaryGetValue( classesToMethodDictionaries, theClass ) ;
key = dict ? (id)CFDictionaryGetValue( dict, selector ) : nil ;
if ( key )
{
CFMutableDictionaryRef classDict = (CFMutableDictionaryRef)CFDictionaryGetValue( classesToMethodDictionaries, aClass ) ;
if ( !classDict )
{
classDict = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, NULL, & kCFTypeDictionaryValueCallBacks ) ;
CFDictionarySetValue( classesToMethodDictionaries, aClass, classDict ) ;
CFRelease( classDict ) ;
}
// CFRetain(key);
CFDictionarySetValue( classDict, selector, key ) ;
break ;
}
theClass = [ theClass superclass ] ;
}
}
return key ;
}
#pragma mark - NSString (PropertyContainer)
@implementation NSString (PropertyContainer)
-(NSString*)uppercaseFirstLetter
{
if ( self.length < 2 )
{
return [ self lowercaseString ] ;
}
return [ [ [ self substringToIndex:1 ] lowercaseString ] stringByAppendingString:[ self substringFromIndex:1 ] ] ;
}
-(NSString*)lowercaseFirstLetter
{
if ( self.length < 2 )
{
return [ self uppercaseString ] ;
}
return [ [ [ self substringToIndex:1 ] uppercaseString ] stringByAppendingString:[ self substringFromIndex:1 ] ] ;
}
@end
@ngabel
Copy link
Author

ngabel commented May 3, 2011

remove dependency on NSString+Utilities category

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment