How to make the fowling data conversion: NSArray to char - objective-c

Well I'm currently calling a method that requires one char input method, but I the data for it is loaded from a file than putted into an array and then I want to convert one of the array's elements to an const char (all the array's elements are URL's). What basically I'm trying to do is to make the program to load a specific file and then put the lines separately into the array's elements (I mean: 1 line = 1 new array element), and then I made a for loop like this:
NSUInteger nElements = [array count];
int i;
for (i = 0; i<nElements; i++) {
const char* urlName = [[array objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding]; // I don't know if this is correct but don't works :)
}

If it's an array of NSURL objects you'd have to convert them to strings like this:
const char* urlName = [[[array objectAtIndex:i] absoluteString] UTF8String];

Assuming it's an array of NSString, you could do this:
const char* urlName = [[array objectAtIndex:i] UTF8String];

Related

Store user input in array objective-c

i am trying to get input from user and want to store it in an array.
int main(int argc, const char * argv[]) {
#autoreleasepool
{
int i;
char name[10];
NSMutableArray *myarray=[[NSMutableArray alloc]init];
for (i=0; i<10; i++)
{
scanf("%c",name);
[myarray addObject:i];
}
}
return 0;
}
You are trying to insert a non Object in NSMutableArray.
NSMutableArray can store objects only,
char and int are data types of c language which are not treated as objects in Objective C.
First you need to convert them into objects then You can insert.
Try with this:
[myarray addObject:#(i)]; or
[myarray addObject:[NSNumber numberWithInt:i]];
for name:
[NSString stringWithFormat:#"%c",name]
A textfield will hold user input. Fetch value from the textfield and add it to the array.
arryData = [[NSMutableArray alloc] initWithObjects:#"#&", textFieldinput.text, nil];
This will work better.

Char (hex representation) from NSString

I have a C char array in iOS that looks like this:
static char aStr[MY_STRING_LENGTH] = {0xc0,0xa7,0x82};
When I inspect it on the console (p aStr), I get output that looks like:
(char [MY_STRING_LENGTH]) $1 = "\xc0\xa7\x82"
and that is all fine. However, I need to put that original string in a plist, and read it in as config data. If I type my entry in the plist as a NSString, how can I get the C char array out with the same values? So far, everything I have tried seems to translate the hex values into something else.
I have tried things like:
NSString *newStr = [stringFromPlist UTF8String];
Or breaking the NSString into an array with:
NSArray *arr = [stringFromPlist componentsSeparatedByString:#","];
and then iterating and converting with:
char newArr[MY_STRING_LENGTH];
for (int i = 0; i < MY_STRING_LENGTH; i++) {
newArr[i] = [arr[i] UTF8String];
}
but so far nothing seems to do what I need. I keep ending up with values in the char array that contain the "0x" instead of the "\x".
My C chops are FAR too rusty for this, so I am hoping someone can point out my error.
Cheers!
I don't know if there is a more elegant solution, but you could try:
NSString *stringFromPlist = #"0xc0,0xa7,0x82";
NSArray *arr = [stringFromPlist componentsSeparatedByString:#","];
char newArr[MY_STRING_LENGTH];
for (int i = 0; i < MY_STRING_LENGTH; i++) {
unsigned result = 0;
NSScanner *scanner = [NSScanner scannerWithString:arr[i]];
[scanner scanHexInt:&result];
newArr[i] = result;
}

Convert one NSArray filled with NSStrings to a UTF8String vector

So I was wondering, is there some quick way of converting one NSArray filled with NSStrings to the equivalent UTF8string values?
I want to store some parameter configuration in a NSArray and then use them in a function that takes (int argv, const char *argv[]) as arguments.
I implemented this in a convoluted way
int argc = [gameParameters count];
const char **argv = (const char **)malloc(sizeof(const char*)*argc);
for (int i = 0; i < argc; i++) {
argv[i] = (const char *)malloc(sizeof(char)*[[gameParameters objectAtIndex:i] length]+1);
strncpy((void *)argv[i], [[gameParameters objectAtIndex:i] UTF8String], [[gameParameters objectAtIndex:i] length]+1);
}
but I'm not really happy with and cleaning up memory is tedious.
Do you know a better way to achieve this result?
Your current implementation is not correct if the string contains non-ASCII characters. For example, the string #"é" (SMALL LETTER E WITH ACUTE) has length 1, but the UTF-8 sequence "C3 A9" has 2 bytes. Your code would not allocate enough memory for that string.
(In other words: [string length] returns the number of Unicode characters in the string, not the number of bytes of the UTF-8 representation.)
Using strdup(), as suggested by Kevin Ballard, would solve this problem:
argv[i] = strdup([[gameParameters objectAtIndex:i] UTF8String]);
But you should also check if duplicating the strings is necessary at all. If you call the function in the current autorelease context, the following would be sufficient:
int argc = [gameParameters count];
const char **argv = (const char **)malloc(sizeof(const char*)*argc);
for (int i = 0; i < argc; i++) {
argv[i] = [[gameParameters objectAtIndex:i] UTF8String];
}
yourFunction(argc, argv);
free(argv);

Iterate through NSData bytes

How can I iterate through [NSData bytes] one by one and append them to an NSMutableString or print them using NSLog()?
Rather than appending bytes to a mutable string, create a string using the data:
// Be sure to use the right encoding:
NSString *result = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
If you really want to loop through the bytes:
NSMutableString *result = [NSMutableString string];
const char *bytes = [myData bytes];
for (int i = 0; i < [myData length]; i++)
{
[result appendFormat:#"%02hhx", (unsigned char)bytes[i]];
}
Update! Since iOS 7, there's a new, preferred way to iterate through all of the bytes in an NSData object.
Because an NSData can now be composed of multiple disjoint byte array chunks under the hood, calling [NSData bytes] can sometimes be memory-inefficient, because it needs to flatten all of the underlying chunks into a single byte array for the caller.
To avoid this behavior, it's better to enumerate bytes using the enumerateByteRangesUsingBlock: method of NSData, which will return ranges of the existing underlying chunks, which you can access directly without needing to generate any new array structures. Of course, you'll need to be careful not to go poking around inappropriately in the provided C-style array.
NSMutableString* resultAsHexBytes = [NSMutableString string];
[data enumerateByteRangesUsingBlock:^(const void *bytes,
NSRange byteRange,
BOOL *stop) {
//To print raw byte values as hex
for (NSUInteger i = 0; i < byteRange.length; ++i) {
[resultAsHexBytes appendFormat:#"%02x", ((uint8_t*)bytes)[i]];
}
}];

Storing data in string into an integer array

I have some data into a string and I wish to store that data in an integer array... Below is the code.
int valMines[256];
// 'b' is NSString with 256 values in it.
for(int i=0; i<[b length]; i++){
valMines[i] = [NSString stringWithFormat:#"%d", [b characterAtIndex:i]];
NSLog(#"valMines1 is %#", valMines[i]);
}
I am getting a warning and due to that my application is not getting loaded:
Assignment makes integer from pointer without a cast.
Please help
Your valMins is an integer array and you are assigning NSString to it. Probably you are looking something like this:
unichar valMines[256]; // make it unichar instead of int
// 'b' is NSString with 256 values in it.
for(int i=0; i<[b length]; i++){
valMines[i] = [b characterAtIndex:i]; // get and store the unichar
NSLog(#"valMines1 is %d", valMines[i]); // format specifier is %d, not %#
}