Skip to content

Instantly share code, notes, and snippets.

@drodriguez
Created December 22, 2010 22:18
Show Gist options
  • Save drodriguez/752184 to your computer and use it in GitHub Desktop.
Save drodriguez/752184 to your computer and use it in GitHub Desktop.
Objective-C++ NSString wrapper example
// $ g++ -o test -framework Foundation -Wall test.mm
// $ ./test
// The string length is 12
// The string third char value is 108
// The string is Hello World!
#include <iostream>
#import <Foundation/Foundation.h>
class MyCppNSStringWrapper
{
public:
MyCppNSStringWrapper(const char* str);
virtual ~MyCppNSStringWrapper();
unsigned int length() const;
short characterAtIndex(unsigned int index) const;
const char* UTF8String() const;
private:
NSString* _internal;
};
MyCppNSStringWrapper::MyCppNSStringWrapper(const char* str)
{
_internal = [[NSString alloc] initWithCString:str
encoding:NSUTF8StringEncoding];
}
MyCppNSStringWrapper::~MyCppNSStringWrapper()
{
[_internal release];
_internal = nil;
}
unsigned int MyCppNSStringWrapper::length() const
{
return [_internal length];
}
short MyCppNSStringWrapper::characterAtIndex(unsigned int index) const
{
return [_internal characterAtIndex:index];
}
const char* MyCppNSStringWrapper::UTF8String() const
{
return [_internal UTF8String];
}
extern "C" int main(int argc, char** argv)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
MyCppNSStringWrapper* s = new MyCppNSStringWrapper("Hello World!");
std::cout << "The string length is " << s->length() << std::endl;
std::cout << "The string third char value is " << s->characterAtIndex(2) << std::endl;
std::cout << "The string is " << s->UTF8String() << std::endl;
[pool release];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment