将自定义对象序列化为PLIST

时间:2012-10-04 09:42:47

标签: objective-c ios serialization plist nscoding

我希望能够获取一个对象并将其所有属性写入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应用程序之间传输输出,所以需要通过中间的,独立于平台的格式

当然,我可能完全忽略了这一点,如果我有请告诉,并且一如既往,任何帮助都是有用的。

祝你好运

戴夫

P.S。

以下是获取对象属性名称的方法:

- (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;
}

1 个答案:

答案 0 :(得分: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;
}