首页 > 解决方案 > 如何将 NSArray 的项目转换为 utf16 (char16_t)?

问题描述

我有一个函数可以获取目录的所有内容,无论是文件还是目录,并且我正在使用contentsOfDirectoryAtPath它来收集目录的内容,然后我将文件/目录的名称保存到一个名为的容器中,该容器contentsStore接受 UTF-16 字符串的键和值项char16_t。查看以下代码以使您的愿景清晰:

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");
    }
}

请注意,我没有发布整个代码,因为它很大,但我只是添加了与问题相关的重要部分。另外,我使用 Objective-C 作为桥梁来实现在 macOS 中使用 Cocoa 的目标,但我使用的主要语言是 C++,因此,整个代码是 C++/Objective-C 的组合。

如何制作将objectAtIndex项目内容输出为 UTF-16 的方法char16_t

标签: nsarrayobjective-c++utf-16

解决方案


下面会给你一个想法。这[Filemanager defaultmanager]实际上是在支持您的任务。您可以将路径转换为 ​​C 字符串,然后再转换为char16_taka的字符串basic_string<char16_t>

NSString *_dirPath = [[NSBundle mainBundle] bundlePath];
NSError *error = nil;
NSFileManager *manager = [[NSFileManager defaultManager] init];
NSArray *dirContents = [manager contentsOfDirectoryAtPath:_dirPath error:&error];

if (!error && dirContents.count ) {

    for(unsigned int i = 0; i < [dirContents count]; i++){
        NSString *path = [dirContents objectAtIndex:i];
        BOOL isDir;
        std::string usingkey = "file";

        if ([manager fileExistsAtPath:path isDirectory:&isDir] && isDir) {
            usingkey = "directory";
        }
        
        const char *fileRepresentation = [manager fileSystemRepresentationWithPath:path];

        // function declared below..
        std::u16string char16string = to_utf16(fileRepresentation);

        // and use it to store your C++ storageObject, value&key pair
        // don't know of what datatype is usingkey in your source 
        // just assumed std::string 
        contentsStore.Add(char16string, usingkey);

    }
}

您必须在.mm实施中包含以下内容

#include <string>
#include <codecvt>
#include <iostream>

@implementation Yourclassname 

//std::u16string is same as basic_string<char16_t>
std::u16string to_utf16( std::string str )
{ return std::wstring_convert< std::codecvt_utf8_utf16<char16_t>, char16_t >{}.from_bytes(str); }

@end

推荐阅读