Skip to content

Commit f6d27f7

Browse files
authored
[NSArray] Implementation of file serialization functionality
1 parent a2904a2 commit f6d27f7

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

Foundation/NSArray.swift

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -397,8 +397,20 @@ open class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCo
397397
return objects
398398
}
399399

400-
open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool { NSUnimplemented() }
401-
open func write(to url: URL, atomically: Bool) -> Bool { NSUnimplemented() }
400+
open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool {
401+
return write(to: URL(fileURLWithPath: path), atomically: useAuxiliaryFile)
402+
}
403+
404+
// the atomically flag is ignored if url of a type that cannot be written atomically.
405+
open func write(to url: URL, atomically: Bool) -> Bool {
406+
do {
407+
let pListData = try PropertyListSerialization.data(fromPropertyList: self, format: .xml, options: 0)
408+
try pListData.write(to: url, options: atomically ? .atomic : [])
409+
return true
410+
} catch {
411+
return false
412+
}
413+
}
402414

403415
open func objects(at indexes: IndexSet) -> [Any] {
404416
var objs = [Any]()
@@ -571,8 +583,20 @@ open class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCo
571583
return lastEqual ? result + 1 : result
572584
}
573585

574-
public convenience init?(contentsOfFile path: String) { NSUnimplemented() }
575-
public convenience init?(contentsOfURL url: URL) { NSUnimplemented() }
586+
public convenience init?(contentsOfFile path: String) {
587+
self.init(contentsOfURL: URL(fileURLWithPath: path))
588+
}
589+
590+
public convenience init?(contentsOfURL url: URL) {
591+
do {
592+
guard let plistDoc = try? Data(contentsOf: url),
593+
let plistArray = try PropertyListSerialization.propertyList(from: plistDoc, options: [], format: nil) as? Array<Any>
594+
else { return nil }
595+
self.init(array: plistArray)
596+
} catch {
597+
return nil
598+
}
599+
}
576600

577601
override open var _cfTypeID: CFTypeID {
578602
return CFArrayGetTypeID()

0 commit comments

Comments
 (0)