nsarray - 如何将 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
?
解决方案
下面会给你一个想法。这[Filemanager defaultmanager]
实际上是在支持您的任务。您可以将路径转换为 C 字符串,然后再转换为char16_t
aka的字符串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
推荐阅读
- python - 通配符中的 Snakemake 特殊符号
- python - str.strip() 的文档是否具有误导性?
- android - EditText 显示带有提示的文本
- excel - 选择新值后重置下拉菜单
- android - 值从edittext传递到veriables
- python - 在 Python 中转置、旋转和组合二维数组
- r - 我对 R 中的“重复”功能有疑问
- python - 我在使用 subprocess 命令时遇到错误
- javascript - Android Studio React Native 构建失败
- if-statement - SAS 9.4M6中where语句和if语句之间处理char有什么区别