全部博文(322)
分类: BSD
2012-04-06 10:36:54
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 | @interface Foo : NSObject { NSString *_property1; NSString *_property2; } @property(nonatomic,retain)NSString *property1; @property(nonatomic,retain)NSString *property2; @implementation Foo @synthesize property1 = _property1; @synthesize property2 = _property2; - (id)init { self = [super init]; if (self) { _property1 = @"haha"; _property2 = @"hehe"; } return self; } - (void)dealloc { [super dealloc]; } |
1 2 3 4 5 6 7 8 9 10 11 | Foo *foo = [[Foo alloc] init]; NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: foo.property1,@"property1", foo.property2,@"property2", nil]; [[JSONSerializer serializer] serializer:dict]; |
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 | Foo *foo = [[Foo alloc] init]; id fooClass = objc_getClass("Foo"); unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList(fooClass, &outCount); //获取该类的所有属性 for (i = 0; i < outCount; i++) { objc_property_t property = properties; //property_getName()返回属性的名字 在Foo中分别是 property1和property2 //property_getAttributes()返回属性的属性,如是retain还是copy之类的 //这个方法输出了该类所有的属性名与对应的属性的属性(好绕口啊) NSLog(@"%s %s\n", property_getName(property), property_getAttributes(property)); } |
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 | NSString *className = NSStringFromClass([theObject class]); const char *cClassName = [className UTF8String]; id theClass = objc_getClass(cClassName); unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList(theClass, &outCount); NSMutableArray *propertyNames = [[NSMutableArray alloc] initWithCapacity:1]; for (i = 0; i < outCount; i++) { objc_property_t property = properties; NSString *propertyNameString = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; [propertyNames addObject:propertyNameString]; [propertyNameString release]; NSLog(@"%s %s\n", property_getName(property), property_getAttributes(property)); } NSMutableDictionary *finalDict = [[NSMutableDictionary alloc] initWithCapacity:1]; for(NSString *key in propertyNames) { SEL selector = NSSelectorFromString(key); id value = [theObject performSelector:selector]; if (value == nil) { value = [NSNull null]; } [finalDict setObject:value forKey:key]; } [propertyNames release]; NSString *retString = [[CJSONSerializer serializer] serializeDictionary:finalDict]; [finalDict release]; return retString; |