0

我做了这个方法

-(NSMutableArray *)getProperties:(id)c
{
    NSString *propertyName;
    unsigned int outCount, i;
    NSMutableArray *propertieNames = [[NSMutableArray alloc] initWithObjects: nil];

    objc_property_t *properties = class_copyPropertyList(c, &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        propertyName = [NSString stringWithUTF8String:property_getName(property)];
        [propertieNames addObject:propertyName];
    }
    return propertieNames;
}

我用这个

NSMutableArray *propertiesNames = [self getProperties:[self class]];

我想用这个

NSMutableArray *propertiesNames = [[self class] getProperties];

如何将类别添加到 Class 类。也许 Class 类不是 Object....

我尝试将类别添加到类

#import "Class+SN.h"

@implementation Class (SN)

@end

我有错误

Cannot find interface declaration for 'Class'
4

1 回答 1

1

如果你想要一个类方法,你必须使用+而不是-. 在类方法中,self指的是类,所以可以cself. 的文档class_copyPropertyList说您需要稍后使用 释放列表free(),否则您会泄漏内存。

+ (NSArray *) getProperties
{
    NSString *propertyName;
    unsigned int outCount, i;
    NSMutableArray *propertyNames = [NSMutableArray array];

    objc_property_t *properties = class_copyPropertyList(self, &outCount);
    for (i = 0; i < outCount; i++)
    {
        objc_property_t property = properties[i];
        propertyName = [NSString stringWithUTF8String:property_getName(property)];
        [propertyNames addObject:propertyName];
    }

    free(properties);

    return propertyNames;
}

Also, Objective-C method names rarely use get. Many methods with get in the name imply that they have output parameters or that the caller should provide their own buffer (for examples of when to use get in the name, see getCharacters:range:, and also getStreamsToHost:port:inputStream:outputStream:). This convention means your method would be more appropriately named properties or classProperties etc.

于 2013-01-16T04:45:40.123 回答