【发布时间】:2023-04-02 03:48:01
【问题描述】:
我希望能够获取一个对象并将其所有属性写入 PLIST。我到目前为止:
// Get the properties of the parent class
NSMutableArray *contentViewPropertyNames = [self propertyNamesOfObject:[contentView superclass]];
// Add the properties of the content view class
[contentViewPropertyNames addObjectsFromArray:[self propertyNamesOfObject:contentView]];
// Get the values of the keys for both the parent class and the class itself
NSDictionary *keyValuesOfProperties = [contentView dictionaryWithValuesForKeys:contentViewPropertyNames];
// Write the dictionary to a PLIST
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathAndFileName = [documentsDirectory stringByAppendingPathComponent:[dataFileName stringByAppendingString:@".plist"]];
[keyValuesOfProperties writeToFile:pathAndFileName atomically:YES];
一切都好,除了我无法将其写入 PLIST,因为它包含一些不符合 PLIST 的属性,因此 writeToFile:atomically: 失败并返回 NO。
有没有一种好方法可以只序列化那些可序列化为 PLIST 的属性或修改我的对象的基类以使其工作?
我意识到我可以使用NSCoding 归档到二进制文件,但是我需要能够在 MacOS 应用程序和 iOS 应用程序之间传输输出,因此需要通过中间的、平台无关的格式。
当然,我可能完全忽略了这一点,如果我有请告诉我,并且一如既往,任何帮助都是有用的。
最好的问候
戴夫
附言
这是我获取对象属性名称的方法:
- (NSMutableArray *)propertyNamesOfObject:(id)object {
NSMutableArray *propertyNames = nil;
unsigned int count, i;
objc_property_t *properties = class_copyPropertyList([object class], &count);
if (count > 0) {
propertyNames = [[[NSMutableArray alloc] init] autorelease];
for(i = 0; i < count; i++) {
objc_property_t property = properties[i];
const char *propName = property_getName(property);
if(propName) {
NSString *propertyName = [NSString stringWithCString:propName encoding:NSUTF8StringEncoding];
[propertyNames addObject:propertyName];
}
}
}
free(properties);
return propertyNames;
}
【问题讨论】:
标签: objective-c ios serialization plist nscoding