public
Last active

A custom class that lets you use property accessor syntax to set/get member vars. (Works very much like NSManagedObject)

  • Download Gist
ABOUT
1 2 3 4 5 6 7
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
LICENSE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
//
// 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
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
 
//
// 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

remove dependency on NSString+Utilities category

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.