3

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?

Pibomb
  • 59
  • 3
  • 10
  • Yes it is possible. You'd use a bridging cast on each item in the mutable array to a void pointer and store that in the `std::vector`. Examples: https://stackoverflow.com/questions/7298912/convert-nsdictionary-to-stdvector?rq=1 It'd have to be done in Objective-C++ .mm file of course. – Brandon Jun 18 '17 at 14:31
  • Thank you very much. Your comments have been able to get me started. – Pibomb Jun 18 '17 at 17:09
  • @Brandon, sorry but you can use templates of Objective-C++ to create, specification to any Objective-C type. For example: std::set, std::vector<__weak NSObject*>. Second container will store weak references. – Andrew Romanov Jun 21 '17 at 05:27
  • Also don't forget that cast to void* is not safe to ARC. But it is a other story. – Andrew Romanov Jun 21 '17 at 05:31

1 Answers1

6

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.

Andrew Romanov
  • 4,774
  • 3
  • 25
  • 40
  • 1
    nit: I think there is a small optimization where you can initialize the vector and then reserve the amount of memory needed to copy the array (`vectorList.reserve([array count])`). See: https://stackoverflow.com/questions/25108854/initializing-the-size-of-a-c-vector/25108894 – Tomas Reimers Oct 14 '19 at 19:01