2015-05-22 24 views
0

我有我自己的類的數組:如何讀取用NSKeyedArchiver保存的xml文件?

var listofmyclasses = [MyClass]() 

MyClass中我已經實現:

- func encodeWithCoder(aCoder: NSCoder!) 
- init (coder aDecoder: NSCoder!) 

我寫我數組的內容的XML文件,並能正常工作:

  let plistpath = directories[0].stringByAppendingPathComponent("BookmarkArray.plist") 
     let archivedData = NSMutableData() 
     let archiver = NSKeyedArchiver(forWritingWithMutableData: archivedData) 
     archiver.outputFormat = NSPropertyListFormat.XMLFormat_v1_0 
     archiver.encodeObject(listofbookmarks) 
     archiver.finishEncoding() 
     archivedData.writeToFile(plistpath, atomically: true) 

文件以XML格式保存。太好了!

現在的問題是:

如何讀取XML的內容回MyClass的一個新的數組:

var newArray:[MyClass]=getContent(plistpath); 

我試了一下,到目前爲止:

var archivedData2:NSMutableData = NSMutableData(contentsOfFile: plistpath)!; 
let listofmyclasses2 = NSKeyedUnarchiver.unarchiveObjectWithData(archivedData2); 

但listofmyclasses2是零。

+0

使用'NSKeyedUnarchiver'類。 – Gandalf

+0

我嘗試使用NSKeyedUnarchiver進行更新。我不明白如何使用這個類,我沒有找到任何來源。任何幫助? –

+0

http://nshipster.com/nscoding/這個網站會告訴你如何使用nskeyedunarchiver –

回答

1

試試這回讀文件:

let dat : NSData = NSData.dataWithContentsOfMappedFile(plistpath) as NSData 
    let unarchiver = NSKeyedUnarchiver(forReadingWithData: dat) 
    let read_bookmarks = unarchiver.decodeObject() as [MyClass] 
    unarchiver.finishDecoding() 

(當然你肯定想用更好的錯誤檢查:-))

0

NSPropertyListSerialization可以解碼各種編碼的plist像NSPropertyListXMLFormat_v1_0

NSError* error; 
NSData* data = [NSData dataWithContentsOfURL:yourURL options:NSDataReadingMappedIfSafe error:&error]; 
NSDictionary* dict = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable error:&error];