I am getting some weird numbers returned from the characterAtIndex method for Object-C in the iPhone SDK. The code snippet is as follows:
NSString *new_text;
new_text = [new_text stringByAppendingFormat:@"%@",UITextView_1.text];//=a,b,...f
for(int i = 0; i <= 6; i++)
{
char_num = [new_text characterAtIndex:i];
}
I am trying to get the decimal number for the individual character. I am either getting the wrong value each time. Sometimes the value is greater than 8,000! I should be getting back the number 65 through 71.
new_text is a local variable, it’s not initalized, and you send a message to it before assigning a value to it. Unlike newly alloc’d Objective-C objects, local variable values are not zero’d automatically, thus the pointer value of new_text is whatever happened to be that memory location prior to the method’s execution. In other words, your new_text pointer is pointing at a non-deterministic memory location, thus the behavior here is undefined and unpredictable. Usually you’d end up crashing, but by sheer chance you’re pointing at something that looks like a string, but the contents of that string are also non-deterministic. Hence weird character values.
n.b. This is a great example of why it’s good practice to always initialize local variables when they’re declared.