Reputation: 972
I have a c string and need it to break it up into lines (I wont make a NSString of them at this moment). Is there something like an NSMutableArray where I can put this char * in? Or how can I achieve it to make something from the strings what I can access later by index?
Currently I make
char *cline = strtok(data, "\n");
while(cline)
{
...
}
Or is it easier todo this when I read the file from disk?
Upvotes: 1
Views: 3831
Reputation: 642
As others have already pointed out, to store primitive C types such as a in an Obj-C object such as an instance of NSMutableArray
, you would need to wrap them in NSValue
objects first.
As an alternative to doing this - if you are wanting to work with pure C strings in Obj-C, don't forget that you can freely mix C with Objective-C source code, so using a normal C array is a perfectly legitimate solution too.
By wrapping the values into an obj-c array you gain the bounds checking and mutability, but if you keep unwrapping the values to work on them as a C string, you might be better sticking with a plain old C string to begin with, to save the overhead.
If you then want to make an NSString, you can simply use the NSString
convenience method stringWithFormat:
, like so:
char str[50];
// read characters into the buffer from a file...
// When done, convert to an NSString:
NSString *string = [NSString stringWithFormat:@"%s", str];
Upvotes: 1
Reputation: 11597
Use an NSValue to store your char* in an NSMutableArray
Overview
An NSValue object is a simple container for a single C or Objective-C data item. It can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object ids. The purpose of this class is to allow items of such data types to be added to collections such as instances of NSArray and NSSet, which require their elements to be objects. NSValue objects are always immutable.
Upvotes: 2
Reputation: 7331
You cannot insert a C/C++ pointer into an NSMutableArray, unless it is wrapped in a container like an NSValue or other Objective-C class.
It would be a lot easier, if you want an NSMutableArray, to just convert it to an NSString.
NSArray* strings = [[NSString initWithCString:data encoding:NSUTF8StringEncoding] componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]];
Your other options, if you strictly want to stay in the C/C++ realm would be to have a vector of strings or an array of char*.
Upvotes: 1