2016-09-28 15 views
0

我想弄清楚如何使用Swift 3中的數據指針。我在OBJ-C中修改了第10個值文件中的第4個值。我將如何在Swift 3中完成這個任務?在Swift 3中使用指針來修改數據

- (void) modifyFourthValueInFile:(NSString*)filePath { 
    //filePath is a file that contains 10 SInt16 values 
    NSData *data = [NSData dataWithContentsOfFile:filePath]; 
    SInt16 *ourPointer = (SInt16*)data.bytes; 
    ourPointer += 3; // get the 4th value 
    *ourPointer = 1234; // modify the 4th value 
    [data writeToFile:filePath atomically:YES]; 
} 

回答

1

一種可能的方法:

  • 文件讀入到一個Data值。使用withUnsafeMutableBytes()來變異字節。
  • 創建一個UnsafeMutableBufferPointer,這允許通過下標而不是指針算術修改 數據。
  • 將數據寫回到文件中。
  • 使用do/try/catch進行錯誤處理。

實施例:

func modifyFile(filePath: String) { 
    let fileURL = URL(fileURLWithPath: filePath) 
    do { 
     var data = try Data(contentsOf: fileURL) 
     data.withUnsafeMutableBytes { (i16ptr: UnsafeMutablePointer<Int16>) in 
      let i16buffer = UnsafeMutableBufferPointer(start: i16ptr, count: data.count/MemoryLayout<Int16>.stride) 

      i16buffer[3] = 1234 // modify the 4th value 
     } 
     try data.write(to: fileURL, options: .atomic) 
    } catch let error { 
     print(error.localizedDescription) 
    } 
} 
+0

事實上,我發現,在整個創建不需要緩衝步驟,因爲可以直接標中的UnsafeMutablePointer 這樣的:i16ptr [3] = 1234 – kishdude

+0

@kishdude:您是對的,我後來才意識到。緩衝區的可能的優點是:1)邊界檢查2)它是一個集合,所以你可以迭代它的元素。 –