Skip to content

Commit 78f16c0

Browse files
saiHemak“saiHemak”
authored and
“saiHemak”
committed
Implementation of NSMutableDictionary.init(contentsOfFile:)
1 parent 2d80441 commit 78f16c0

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

Foundation/NSDictionary.swift

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -563,8 +563,20 @@ open class NSMutableDictionary : NSDictionary {
563563
super.init(objects: objects, forKeys: keys, count: cnt)
564564
}
565565

566-
public convenience init?(contentsOfFile path: String) { NSUnimplemented() }
567-
public convenience init?(contentsOfURL url: URL) { NSUnimplemented() }
566+
public convenience init?(contentsOfFile path: String) {
567+
self.init(contentsOfURL: URL(fileURLWithPath: path))
568+
}
569+
570+
public convenience init?(contentsOfURL url: URL) {
571+
do {
572+
guard let plistDoc = try? Data(contentsOf: url) else { return nil }
573+
let plistDict = try PropertyListSerialization.propertyList(from: plistDoc, options: [], format: nil) as? Dictionary<AnyHashable,Any>
574+
guard let plistDictionary = plistDict else { return nil }
575+
self.init(dictionary: plistDictionary)
576+
} catch {
577+
return nil
578+
}
579+
}
568580
}
569581

570582
extension NSMutableDictionary {

TestFoundation/TestNSDictionary.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ class TestNSDictionary : XCTestCase {
3131
("test_copying", test_copying),
3232
("test_mutableCopying", test_mutableCopying),
3333
("test_writeToFile", test_writeToFile),
34+
("test_initWithContentsOfFile", test_initWithContentsOfFile),
3435
]
3536
}
3637

@@ -186,6 +187,23 @@ class TestNSDictionary : XCTestCase {
186187
XCTFail("Temporary file creation failed")
187188
}
188189
}
190+
191+
func test_initWithContentsOfFile() {
192+
let testFilePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256))
193+
if let _ = testFilePath {
194+
let d1: NSDictionary = ["Hello":["world":"again"]]
195+
let isWritten = d1.write(toFile: testFilePath!, atomically: true)
196+
if(isWritten) {
197+
let dict = NSMutableDictionary.init(contentsOfFile: testFilePath!)
198+
XCTAssert(dict == d1)
199+
} else {
200+
XCTFail("Write to file failed")
201+
}
202+
removeTestFile(testFilePath!)
203+
} else {
204+
XCTFail("Temporary file creation failed")
205+
}
206+
}
189207

190208
private func createTestFile(_ path: String, _contents: Data) -> String? {
191209
let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().uuidString + "/"

0 commit comments

Comments
 (0)