2012-10-04 81 views
0

我希望能夠獲取對象並將其所有屬性寫出到PLIST。我走到這一步,這一點:將自定義對象序列化到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; 
} 

回答

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; 
} 
+0

這看起來不錯的Jere。我會給它一個去讓你知道我如何繼續。戴夫。 –

+0

該方法看起來不錯,但由於某些原因,我的所有obj類都被報告爲__NSCFString而不是它們的正確類型,因此兼容性檢查將爲每個鍵返回NO。有任何想法嗎? –

+0

嗯,在這方面的任何幫助? http://stackoverflow.com/questions/393873/nsstring-instance-reports-its-class-as-nscfstring –

相關問題