Skip to content

Commit 5143e01

Browse files
committed
Fix decoding NSData from an NSCoder
1 parent 833f572 commit 5143e01

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

Foundation/NSData.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -373,10 +373,10 @@ open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
373373
preconditionFailure("Unkeyed coding is unsupported.")
374374
}
375375
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.data") {
376-
guard let data = aDecoder._decodePropertyListForKey("NS.data") as? NSData else {
376+
guard let data = aDecoder._decodePropertyListForKey("NS.data") as? Data else {
377377
return nil
378378
}
379-
_init(bytes: UnsafeMutableRawPointer(mutating: data.bytes), length: data.length, copy: true)
379+
_init(bytes: UnsafeMutableRawPointer(mutating: data._nsObject.bytes), length: data.count, copy: true)
380380
} else {
381381
let result : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") {
382382
guard let buffer = $0 else { return nil }

TestFoundation/TestNSData.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,7 @@ class TestNSData: XCTestCase {
518518
("test_validateMutation_slice_customBacking_withUnsafeMutableBytes_lengthLessThanLowerBound", test_validateMutation_slice_customBacking_withUnsafeMutableBytes_lengthLessThanLowerBound),
519519
("test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound",
520520
test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound),
521+
("test_nskeyedarchiving", test_nskeyedarchiving),
521522
]
522523
}
523524

@@ -4140,5 +4141,19 @@ extension TestNSData {
41404141
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
41414142
#endif
41424143
}
4144+
4145+
func test_nskeyedarchiving() {
4146+
let bytes: [UInt8] = [0xd, 0xe, 0xa, 0xd, 0xb, 0xe, 0xe, 0xf]
4147+
let data = NSData(bytes: bytes, length: bytes.count)
4148+
4149+
let archiver = NSKeyedArchiver()
4150+
let key = "data"
4151+
data.encode(with: archiver)
4152+
let encodedData = archiver.encodedData
4153+
4154+
let unarchiver = NSKeyedUnarchiver(forReadingWithData: encodedData)
4155+
let decodedData = NSData(coder: unarchiver)
4156+
XCTAssertEqual(data, decodedData)
4157+
}
41434158
}
41444159

0 commit comments

Comments
 (0)