在Person.h 頭文件中atom
@interface Person : NSObject { @private //name爲私有成員變量 NSString *name; } // age 爲成員屬性 @property (nonatomic ,copy) NSString *age;
在viewController.m 中,經過RunTime機制得到對象的全部成員變量和成員屬性。spa
Person *p = [Person new]; unsigned int count = 0; //count記錄變量的數量 // 獲取類的全部成員變量 Ivar *members = class_copyIvarList([Person class], &count); for (int i = 0; i < count; i++) { Ivar ivar = members[i]; // 取得變量名並轉成字符串類型 const char *memberName = ivar_getName(ivar); NSLog(@"變量名 = %s",memberName); } // 獲取類的全部成員屬性 objc_property_t *properties =class_copyPropertyList([Person class], &count); for (int i = 0; i<count; i++) { objc_property_t property = properties[i]; const char* char_f =property_getName(property); NSString *propertyName = [NSString stringWithUTF8String:char_f]; NSLog(@"屬性名 = %@",propertyName); }
打印結果爲code
2016-08-12 11:31:50.225 modifyPrivate[777:143231] 變量名 = name 2016-08-12 11:31:50.226 modifyPrivate[777:143231] 變量名 = _age 2016-08-12 11:31:50.226 modifyPrivate[777:143231] 屬性名 = age