2016-12-02 5 views
0

Swift 3のplistにNSMutableDictionaryの内容を書き込もうとしています。これはObjective-Cで使用した構造ですが、Swiftでは動作しません。以下のコードを実行すると、エラーが発生します。誰が何が間違っているかも考えているのですか?swiftでplistへの書き込みが失敗するのはなぜですか?

let array1 = "\(Int(Value1))" 
let array2 = "\(Int(Value2))" 

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) 
let plistpath = NSURL(fileURLWithPath: paths[0]).appendingPathComponent("myplist9.plist")!.absoluteString 

let dictionary: NSMutableDictionary = ["String":"String"] 
dictionary["Value 1"] = array1 
dictionary["Value 2"] = array2 

if dictionary.write(toFile: plistpath, atomically: false) { 
    print("Success") 
} 
else { 
    print("Error") 
} 
+0

URL関連APIを使用してファイルを書き留めてみませんか?また、配列内のリテラルの "Optional(12)"文字列に注意してください。 – vadian

+0

@vadian私の答えの最後の文章を見てください。 :) – rmaddy

答えて

2

あなたはNSURLabsoluteStringメソッドを使用してファイルパスに変換することができません。 pathメソッドを使用する必要があります。

変更:

let plistpath = NSURL(fileURLWithPath: paths[0]).appendingPathComponent("myplist9.plist")!.path 

そして、あなたはURL、ないNSURLを使用し、スウィフト3使用しているので:

let plistpath = NSURL(fileURLWithPath: paths[0]).appendingPathComponent("myplist9.plist")!.absoluteString 

へ。

let plistpath = URL(fileURLWithPath: paths[0]).appendingPathComponent("myplist9.plist")!.path 

それともURLを取るNSDictionary write(to:atomically:)方法を使用することができます。

+0

それは働いた。早速のご返事ありがとうございます! –

関連する問題