I’m trying to append a string to a file by encoding it as NSUnicodeStringEncoding first. I’m doing this:
NSData *data = [@"data" dataUsingEncoding: NSUnicodeStringEncoding];
NSFileHandle *output = [NSFileHandle fileHandleForUpdatingAtPath:@"file"];
[output seekToEndOfFile];
[output writeData:data];
If I do this a number of times and then take a look at the file I notice that every string added has FFFE prepended to it. But when I switch from NSUnicodeStringEncoding to NSUTF8StringEncoding this prefix goes away.
That’s called a byte-order marker, and is put there because
NSUnicodeStringEncodingdoesn’t specify whether the characters are stored in big or little endian order.To prevent
0xFFFEor0xFEFFfrom appearing at the beginning of a string, use one ofNSUTF16BigEndianStringEncoding,NSUTF16LittleEndianStringEncoding,NSUTF32BigEndianStringEncoding, orNSUTF32LittleEndianStringEncoding, depending on your specific needs. (For reference: Intel and ARM processors as used by Apple are little endian.)