NSMutableArray to std::vector

白昼怎懂夜的黑 提交于 2019-12-11 05:27:58

问题


Is it possible to convert the contents of an NSMutableArray to a std::vector? And if so, should this be done in the Objective-C or C++ code?


回答1:


You can create a vector with any Objective-C type.
For example to store a NSString instance into a vector, you can use next code:

    NSMutableArray<NSString*>* array = [@[@"1", @"2"] mutableCopy];

    __block std::vector<NSString*> vectorList;
    vectorList.reserve([array count]);
    [array enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        vectorList.push_back(obj);
    }];

    for (std::vector<NSString*>::const_iterator iterator = vectorList.cbegin(); iterator != vectorList.cend(); iterator++)
    {
        NSLog(@"%@", *iterator);
    }

You should use it in Objective-C++ files, because C++ does not have syntax for Objective-C (files with mm extension).

If you need to convert a data inside NSMutableArray to different representation, for example, NSNumber to int or NSString to std::string, you should create it by hand.



来源:https://stackoverflow.com/questions/44615381/nsmutablearray-to-stdvector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!