2016-09-28 2 views
0

Swift 3의 데이터에서 포인터를 사용하는 방법을 알아 내려고합니다. OBJ-C에서 10 값 파일의 4 번째 값을 수정하는 다음과 같은 간단한 방법이 있습니다. . 스위프트 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()을 사용하여 바이트를 변경합니다.
  • 을 만들면 포인터 연산 대신 첨자를 사용하여 데이터를 수정할 수 있습니다.
  • 데이터를 다시 파일에 기록하십시오.
  • 오류 처리에는 do/try/catch를 사용하십시오.

예 : 사실 나는 전체가이 같은 직접 UnsafeMutablePointer 첨자 수 있기 때문에 버퍼 단계가 필요하지 않습니다 만드는 것을 발견

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

: [3] = 1234 – kishdude

+0

@kishdude i16ptr : 당신을 맞습니다. 나중에 깨달았습니다. 버퍼의 장점은 다음과 같습니다. 1) 경계 검사 2) 컬렉션이므로 요소를 반복 할 수 있습니다. –

관련 문제