0

我希望能够获取一个对象并将其所有属性写入 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;
}
4

1 回答 1

0

看看能不能在类似情况下应用我最近写的这个函数:

// Property list compatible types: NSString, NSData, NSArray, or NSDictionary */
- (BOOL)isPlistCompatibleDictionary:(NSDictionary *)dict {
    NSSet *plistClasses = [NSSet setWithObjects:[NSString class], [NSData class],
        [NSArray class], [NSDictionary class], [NSDate class], 
        [NSNumber class], nil];

    BOOL compatible = YES;
    NSArray *keys = [dict allKeys];
    for (id key in keys) {
        id obj = [dict objectForKey:key];
        if (![plistClasses containsObject:[obj class]]) {
            NSLog(@"not plist compatible: %@", [obj class]);
            compatible = NO;
            break;
        }
    }

    return compatible;
}
于 2012-10-04T21:34:24.510 回答