How to convert items of NSArray to UTF-16 (char16_t)?

I have a function that gets all contents of directory whether files or directories and I am using contentsOfDirectoryAtPath to collect the content of a directory then I save the names of files/directories into a container called contentsStore which accepts key&value items of UTF-16 string char16_t. look at the following code to make your vision clear:

Code Block
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:_dirPath error:nil];
for(unsigned int i= 0; i< [dirContents count]; i++){
if(isDir){
// `contentsStore` is key&value container that accepts utf-16 string (char16_t)
contentsStore.Add([[dirContents objectAtIndex:i] UTF8String], "directory");
} else {
contentsStore.Add([[dirContents objectAtIndex:i] UTF8String], "file");
}
}


Note that I don't post the entire code because it's big but I just added the important parts that related to the problem. Also, I am using Objective-Cpp just as a bridge to achieve my goal to use Cocoa in mac OS but the main language that I use is Cpp , so, the entire code is a combination of Cpp/Objective-Cpp .

How to make the objectAtIndex method to output the item's content as UTF-16 char16_t?

Replies

FYI, The NSFileManager routines that take path strings are essentially deprecated in favour of their NSURL equivalents. In this case that’d be +contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:. Mind you, that’s irrelevant to this discussion.

The underlying model for NSString is UTF-16. You can access the UTF-16 code units individually using length and -characterAtIndex:. You can access them in bulk using -getCharacters:range:. You can also convert the string to bytes using -dataUsingEncoding:.

IMPORTANT NSString makes no guarantees about normalisation. In some cases you’ll get precomposed characters and in others you’ll get decomposed ones. If your contents store expects a particular normal form, you should enforce that using precomposedStringWithCanonicalMapping and friends.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"