tags:

views:

96

answers:

2
unichar myChar = [myString characterAtIndex:0];
[myNSMutableArray addObject:myChar];

I am trying to insert the first char of a string into an array, to create an array of chars. the first line does not give me an error. The second line however, provides the following error: warning: passing argument 1 of 'addObject:' makes pointer from integer without a cast

This also crashes the application with a "bad address" error. I thought this error was due to a problem with memory allocation. Can someone shed some light on this.

+4  A: 

You can only add objects to an array. unichar is a primitive data type. You have to wrap it in an NSNumber. A unichar is an unsigned short, so you can use:

[myNSMutableArray addObject:[NSNumber numberWithUnsignedShort:[myString characterAtIndex:0]]];
mipadi
I saw this function earlier but this is for a number. I am trying to do the equivalent with an actual character. I could not find the equivalent function for a character so I wrote the original code I posted. Is there a similar function for a character or is this not normally done in objective-c? (Sorry, I am new to the language)
Oh Danny Boy
A character *is* essentially a number (in fact, a `unichar` is just an `unsigned short`).
mipadi
Then there is no way to get the char at index 0 for the word "String", and get the letter S returned? I apologize for the confusion, maybe its not a char I need, maybe its something else?
Oh Danny Boy
"Primitive" Objective-C data types, like characters, integers, and floating point values, are the same as in C. In C, characters are represented by a numerical value. So essentially, a character is just a number in C. When you use `characterAtIndex:`, you get back a "character", but that's really just a numerical value -- in the case of a `unichar`, it's the same thing as an `unsigned short int`.
mipadi
Thanks for the help.
Oh Danny Boy
+2  A: 

One option would be to add the character to your array as a string:

unichar myChar = [myString characterAtIndex:0];
NSString * charString = [NSString stringWithFormat:@"%c", myChar];
[myNSMutableArray addObject:charString];

Note that this is probably overkill.

e.James
This gave me exactly what I was looking for, thank you.
Oh Danny Boy