-
-
Save wongzigii/a9775a3e854eadc289f51a8f072c7256 to your computer and use it in GitHub Desktop.
Converting a std::vector into an NSArray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//clang++ -std=c++11 -stdlib=libc++ -framework Foundation nsarray.mm -o nsarray | |
/* Note: | |
* - libstdc++ has been frozen by Apple at a pre-C++11 version, so you must opt | |
for the newer, BSD-licensed libc++ | |
* - Apple clang 4.0 (based on LLVM 3.1svn) does not default to C++11 yet, so | |
you must explicitly specify this language standard. */ | |
/* @file nsarray.mm | |
* @author Jeremy W. Sherman | |
* | |
* Demonstrates three different approaches to converting a std::vector | |
* into an NSArray. */ | |
#import <Foundation/Foundation.h> | |
#include <algorithm> | |
#include <string> | |
#include <vector> | |
int | |
main(void) | |
{ | |
@autoreleasepool { | |
/* initializer list */ | |
std::vector<std::string> strings = {"a", "b", "c"}; | |
/* uniform initialization */ | |
//std::vector<std::string> strings{"a", "b", "c"}; | |
/* Exploiting Clang's block->lambda bridging. */ | |
id nsstrings = [NSMutableArray new]; | |
std::for_each(strings.begin(), strings.end(), ^(std::string str) { | |
id nsstr = [NSString stringWithUTF8String:str.c_str()]; | |
[nsstrings addObject:nsstr]; | |
}); | |
NSLog(@"nsstrings: %@", nsstrings); | |
/* Using a lambda directly. */ | |
[nsstrings removeAllObjects]; | |
std::for_each(strings.begin(), strings.end(), | |
[&nsstrings](std::string str) { | |
id nsstr = [NSString stringWithUTF8String:str.c_str()]; | |
[nsstrings addObject:nsstr]; | |
}); | |
NSLog(@"nsstrings: %@", nsstrings); | |
/* Now with a range-based for loop. */ | |
[nsstrings removeAllObjects]; | |
for (auto str : strings) { | |
id nsstr = [NSString stringWithUTF8String:str.c_str()]; | |
[nsstrings addObject:nsstr]; | |
} | |
NSLog(@"nsstrings: %@", nsstrings); | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment