有没有办法让某一种类属性的阵列? 例如,如果我有这样的接口
@interface MyClass : NSObject
@property (strong,nonatomic) UILabel *firstLabel;
@property (strong,nonatomic) UILabel *secondLabel;
@end
我可以得到参考实施这些标签不知道他们的名字?
@implementation MyClass
-(NSArray*)getListOfAllLabels
{
?????
}
@end
我知道我可以很容易地做到这一点[NSArray arrayWithObjects:firstLabel,secondLabel,nil]
,但我想以某种类枚举喜欢就做for (UILabel* oneLabel in ???[self objects]???)
所以,更确切地说,你想要的属性的动态,运行时observaion,如果我没有得到它。 做这样的事情(你要反思实现自我这种方法,应用类):
#import <objc/runtime.h>
- (NSArray *)allPropertyNames
{
unsigned count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableArray *rv = [NSMutableArray array];
unsigned i;
for (i = 0; i < count; i++)
{
objc_property_t property = properties[i];
NSString *name = [NSString stringWithUTF8String:property_getName(property)];
[rv addObject:name];
}
free(properties);
return rv;
}
- (void *)pointerOfIvarForPropertyNamed:(NSString *)name
{
objc_property_t property = class_getProperty([self class], [name UTF8String]);
const char *attr = property_getAttributes(property);
const char *ivarName = strchr(attr, 'V') + 1;
Ivar ivar = object_getInstanceVariable(self, ivarName, NULL);
return (char *)self + ivar_getOffset(ivar);
}
使用这样的:
SomeType myProperty;
NSArray *properties = [self allPropertyNames];
NSString *firstPropertyName = [properties objectAtIndex:0];
void *propertyIvarAddress = [self getPointerOfIvarForPropertyNamed:firstPropertyName];
myProperty = *(SomeType *)propertyIvarAddress;
// Simpler alternative using KVC:
myProperty = [self valueForKey:firstPropertyName];
希望这可以帮助。
使用attributeKeys NSObject的方法。
for (NSString *key in [self attributeKeys]) {
id attribute = [self valueForKey:key];
if([attribute isKindOfClass:[UILabel class]])
{
//put attribute to your array
}
}
看看这个链接 。 它是在目标C运行时的客观C包装。
您可以使用类似的代码如下
uint count;
objc_property_t* properties = class_copyPropertyList(self.class, &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);
您必须包括运行头
#import<objc/runtime.h>
uint propertiesCount;
objc_property_t *classPropertiesArray = class_copyPropertyList([self class], &propertiesCount);
free(classPropertiesArray);
通过@ user529758答案不会与ARC工作,它不会显示任何祖先类的属性。
为了解决这个问题,就需要向上遍历类层次结构,并使用ARC兼容[NSObject valueForKey:]
来获得属性值。
Person.h:
#import <Foundation/Foundation.h>
extern NSMutableArray *propertyNamesOfClass(Class klass);
@interface Person : NSObject
@property (nonatomic) NSString *name;
@end
Person.m:
#import "Person.h"
#import <objc/runtime.h>
NSMutableArray *propertyNamesOfClass(Class klass) {
unsigned int count;
objc_property_t *properties = class_copyPropertyList(klass, &count);
NSMutableArray *rv = [NSMutableArray array];
for (unsigned int i = 0; i < count; i++)
{
objc_property_t property = properties[i];
NSString *name = [NSString stringWithUTF8String:property_getName(property)];
[rv addObject:name];
}
free(properties);
return rv;
}
@implementation Person
- (NSMutableArray *)allPropertyNames {
NSMutableArray *classes = [NSMutableArray array];
Class currentClass = [self class];
while (currentClass != nil && currentClass != [NSObject class]) {
[classes addObject:currentClass];
currentClass = class_getSuperclass(currentClass);
}
NSMutableArray *names = [NSMutableArray array];
[classes enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(Class currentClass, NSUInteger idx, BOOL *stop) {
[names addObjectsFromArray:propertyNamesOfClass(currentClass)];
}];
return names;
}
- (NSString*)description {
NSMutableArray *keys = [self allPropertyNames];
NSMutableDictionary *properties = [NSMutableDictionary dictionaryWithCapacity:keys.count];
[keys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) {
properties[key] = [self valueForKey:key];
}];
NSString *className = NSStringFromClass([self class]);
return [NSString stringWithFormat:@"%@ : %@", className, properties];
}
Student.h:
#import "Person.h"
@interface Student : Person
@property (nonatomic) NSString *studentID;
@end
Student.m:
#import "Student.h"
@implementation Student
@end
main.m文件:
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Student *student = [[Student alloc] init];
student.name = @"John Doe";
student.studentID = @"123456789";
NSLog(@"student - %@", student);
}
return 0;
}
serhats的解决方案是大不幸的是它并不适用于iOS的工作(如你所提到的)(这个问题被标记为iOS)。 一种解决方法是获取对象的NSDictionary中表示,然后正常访问作为键值对。 我会建议NSObject的类别:
页眉文件:
@interface NSObject (NSDictionaryRepresentation)
/**
Returns an NSDictionary containing the properties of an object that are not nil.
*/
- (NSDictionary *)dictionaryRepresentation;
@end
实现的文件:
#import "NSObject+NSDictionaryRepresentation.h"
#import <objc/runtime.h>
@implementation NSObject (NSDictionaryRepresentation)
- (NSDictionary *)dictionaryRepresentation {
unsigned int count = 0;
// Get a list of all properties in the class.
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:count];
for (int i = 0; i < count; i++) {
NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
NSString *value = [self valueForKey:key];
// Only add to the NSDictionary if it's not nil.
if (value)
[dictionary setObject:value forKey:key];
}
free(properties);
return dictionary;
}
@end
从这篇文章借用: http://hesh.am/2013/01/transform-properties-of-an-nsobject-into-an-nsdictionary/
这样,你可以做提到serhats类似的东西:
for (NSString *key in objectDic.allKeys) {
if([objectDic[key] isKindOfClass:[UILabel class]])
{
//put attribute to your array
}
}