वहाँ NSObject पर कोई allKeys
है।
NSObject + PropertyArray.h
@interface NSObject (PropertyArray)
- (NSArray *) allKeys;
@end
NSObject + PropertyArray.m
#import <objc/runtime.h>
@implementation NSObject (PropertyArray)
- (NSArray *) allKeys {
Class clazz = [self class];
u_int count;
objc_property_t* properties = class_copyPropertyList(clazz, &count);
NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++) {
const char* propertyName = property_getName(properties[i]);
[propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
}
free(properties);
return [NSArray arrayWithArray:propertyArray];
}
@end
उदाहरण::
#import "NSObject+PropertyArray.h"
...
MyObject *obj = [[MyObject alloc] init];
obj.a = @"Hello A"; //setting some values to attributes
obj.b = @"Hello B";
//dictionaryWithValuesForKeys requires keys in NSArray. You can now
//construct such NSArray using `allKeys` from NSObject(PropertyArray) category
NSDictionary *objDict = [obj dictionaryWithValuesForKeys:[obj allKeys]];
//Resurrect MyObject from NSDictionary using setValuesForKeysWithDictionary
MyObject *objResur = [[MyObject alloc] init];
[objResur setValuesForKeysWithDictionary:objDict];
यह बहुत आसान है, और setValuesForPropertiesWithKeys जाने का रास्ता है। यह वही करता है जो मेरा कोड करता है, और यह बनाया गया है! अच्छा लगता है। –
यह एक शानदार तरीका है। Objc_ * एपीआई के संयोजन के साथ इसका उपयोग करके, आप एक ऑटो-सीरियलाइजिंग क्लास बना सकते हैं (ताकि आप उन बोझिल-इनिट विथकोडर को लिखना बंद कर सकें: और -कोडकथकोडर: विधियां) – retainCount
बहुत बढ़िया। यह काम में आने वाला है। –