Is it possible to give an instance of object to a function and the function return the value of all attributes for this instance ?? the function should work for any class
Asked
Active
Viewed 99 times
0
-
2Note that such a code is usually just a workaround for bad architecture. Although it is often useful for debugging or testing. – Sulthan May 26 '13 at 15:19
-
What @Sulthan said. If this code and the answers to your other questions are used beyond debugging or pure academic curiosity, you are heading down a path that will produce a very difficult, very fragile, codebase. Objective-C was simply not designed for this level of introspection based programming. – bbum May 26 '13 at 18:07
1 Answers
2
This is the solution:
unsigned int numberOfAttributs;
objc_property_t *attributes = class_copyPropertyList([obj class], &numberOfAttributes);
for (unsigned int i = 0; i < numberOfAttributes; i++) {
objc_property_t attribute = attributes[i];
NSString *attributeName = [NSString stringWithUTF8String: property_getName(attribute)];
NSLog(@"%@", attributeName);
id attributeValue = [obj valueForKey:attributeName];
NSLog(@"%@", attributeValue);
}

Burhanuddin Sunelwala
- 5,318
- 3
- 25
- 51
-
for value, you could try:- [obj valueForKey:@"property_getName(attribute)"]; Try it and then let me know the success – Burhanuddin Sunelwala May 26 '13 at 14:35
-
-
@bbum `valueForKey` will always return an object, even if it's a `NSValue`. – Sulthan May 26 '13 at 14:56
-
I have fixed the types to `unsigned` and the first parameter of `class_copyPropertyList`. – Sulthan May 26 '13 at 14:58
-
property_getName return a 'const char *' not an NSString, so this answer will crash ... – Emmanuel May 26 '13 at 15:42
-
Note that this is going to barf on properties that return structs and it is also going to miss any setter/getter pairs that are not declared as @property. – bbum May 26 '13 at 18:08