我有一個類中的方法,它somethign這樣的:的NSData的dataWithBytesNoCopy和將writeToFile
@implementation NSData (additions)
- (id)someFunc {
char *buffer = malloc(255);
NSUInteger length = 0;
while (true) {
// . . . fill buffer[length++];
}
realloc(buffer, length);
return [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
}
然後我想寫返回的數據(也稱之爲NSData的* FILEDATA):
NSError *error;
NSData fileData = [NSData someFunc];
[fileData writeToFile:somePath options:NSDataWritingAtomic error:&error];
我收到一個錯誤:
Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x20deffd0 {NSFilePath=/Users/user/Library/Application Support/iPhone Simulator/4.3/Applications/4C315580-153D-4FA7-9474-E17B58832515/Library/Caches/file.pdf, NSUnderlyingError=0x20de1fe0 "The operation couldn’t be completed. Bad address"}
該路徑存在且有效。我認爲問題是返回的NSData僅僅是一個用malloc分配的數組的輕量包裝,writeToFile不知道如何處理這個問題。有沒有人看到我在做什麼錯了?
您需要保存由realloc的返回地址:'緩衝區= realloc的(緩衝區長度);' – DarkDust
@DarkDust這是問題,請做出回答我會接受它。 –