gpt4 book ai didi

objective-c - 在 Objective-C 中获取类属性名称的字符串值

转载 作者:太空狗 更新时间:2023-10-30 04:01:42 29 4
gpt4 key购买 nike

我有以下类定义。

联系人.h

#import <CoreData/CoreData.h>


@interface Contact : NSManagedObject
{
}

@property (nonatomic, retain) NSString * City;
@property (nonatomic, retain) NSDate * LastUpdated;
@property (nonatomic, retain) NSString * Country;
@property (nonatomic, retain) NSString * Email;
@property (nonatomic, retain) NSNumber * Id;
@property (nonatomic, retain) NSString * ContactNotes;
@property (nonatomic, retain) NSString * State;
@property (nonatomic, retain) NSString * StreetAddress2;
@property (nonatomic, retain) NSDate * DateCreated;
@property (nonatomic, retain) NSString * FirstName;
@property (nonatomic, retain) NSString * Phone1;
@property (nonatomic, retain) NSString * PostalCode;
@property (nonatomic, retain) NSString * Website;
@property (nonatomic, retain) NSString * StreetAddress1;
@property (nonatomic, retain) NSString * LastName;

@end

是否可以通过名称获取包含所有属性的 NSString 对象数组?

数组看起来像这样......

[@"City", @"LastUpdated", @"Country", .... ]

解决方案(根据评论更新)

感谢 Dave 的回答,我能够编写以下要使用的方法

- (NSMutableArray *) propertyNames: (Class) class { 
NSMutableArray *propertyNames = [[NSMutableArray alloc] init];
unsigned int propertyCount = 0;
objc_property_t *properties = class_copyPropertyList(class, &propertyCount);

for (unsigned int i = 0; i < propertyCount; ++i) {
objc_property_t property = properties[i];
const char * name = property_getName(property);
[propertyNames addObject:[NSString stringWithUTF8String:name]];
}
free(properties);
return [propertyNames autorelease];
}

最佳答案

是的!给你:

#import <objc/runtime.h>

//somewhere:
unsigned int propertyCount = 0;
objc_property_t * properties = class_copyPropertyList([self class], &propertyCount);

NSMutableArray * propertyNames = [NSMutableArray array];
for (unsigned int i = 0; i < propertyCount; ++i) {
objc_property_t property = properties[i];
const char * name = property_getName(property);
[propertyNames addObject:[NSString stringWithUTF8String:name]];
}
free(properties);
NSLog(@"Names: %@", propertyNames);

警告:在浏览器中输入代码。

关于objective-c - 在 Objective-C 中获取类属性名称的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3001441/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com