问题
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