【问题标题】:Converting std::map to Objective-C NSMutableArray elements将 std::map 转换为 Objective-C NSMutableArray 元素
【发布时间】:2012-11-24 13:52:12
【问题描述】:

我想将 std::map 的值转换为 NSMutableArray 元素。
我的 CPP 代码正在使用接口函数将 std::map(带有一个 int 和 std::string)传递给一个 Objective-C 函数。

但我无法将此 std::map 转换为 NSMutableArray。

CPP Code:
------------------------------------------------------------------    
typedef std::map<int, std::string> TemList;
temList temList;
temList[10]="an element";
temList[23]="another element";
temList[545]="last";

passing this map to an objective-c code using interface function. 

Objective-c Code
------------------------------------------------------------------  
- (void) testListUpdate:(const TemList&) pList
{
    NSMutableArray *mArray = [NSMutableArray alloc]init];
    

    for (TemList::const_iterator ii = pList.begin(); ii != pList.end(); ++ii)
    {
        ListItem item = [[ListItem alloc] init]
        
        // PROBLEM **** I am Not able to convert this ******
        item.name = ii->second.c_str();
        item.mId = (int) ii->first;
    
        [mArray addObject:item];
    
        //printf("OBJC Value[%s]: Key[%d]\n", ii->second.c_str(), ii->first);
    }
}

// Interface function implementation 
void interfaceListUpdate(void *self, const TemList& pList)
{
    printf("ObjectiveC Interface Function size[%d]\n", pList.size());
    [(id) self testListUpdate:pList];
}

// Using this struct as Array item
@interface ListItem : NSObject
{
    NSString *name;
    int mId;
}

@end

我还想使用mArray 来显示表格视图行。
我该怎么做。

【问题讨论】:

  • c_str() 返回什么? item.name 应该是什么(它是什么类)?
  • std::string::c_str() 返回 C++ string 对象表示的字符串的纯 C 字符数组(因为 std::string 的内部存储是不透明的)

标签: objective-c xcode cocoa


【解决方案1】:

随便用

NSString *string = [NSString stringWithCString:cppString.c_str() 
                                      encoding:NSUTF8StringEncoding];

或任何NSStringEncoding 适用于您的特定内容!

【讨论】:

    【解决方案2】:

    您必须将您的 std::string 转换为 NSString。不知道要使用的确切 std::string 方法,但您应该这样做:

    [[NSString alloc] initWithCharacters:ii->second.c_str() length:ii->second.length()]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多