Integer Casting in dealing with strings in Cocoa
I have what I hope to be a pretty simple problem. I'm very simply trying to convert a char to it's lowercase version. Here's my code:
- (IBAction)click:(id)sender {
[outputLabel setText:[inputField text]];
NSString* textFieldString = [inputField text];
NSLog(@"String is %@", textFieldString);
int textFieldLength = textFieldString.length;
UniChar* currChar = [textFieldString characterAtIndex:0];
NSLog(@"First char is %c", currChar);
NSLog(@"Length is %i", textFieldLen开发者_如何学Gogth);
//currChar = [currChar lowercaseString];
//NSLog(@"Lowercase char is %c", currChar);
}
It's giving me a the following error:
Initialization makes pointer from integer without a cast on the line:
NSString* currChar = [textFieldString characterAtIndex:0];
However, when looking in the documentation, it says that the method characterAtIndex:
returns a char, not an integer. What gives?
characterAtIndex
returns unichar
which is an unsigned short
. The line should be
unichar currChar = [textFieldString characterATtIndex:0];
Also, you can just use lowercaseString
to get the lowercase of the entire NSString
:
NSString *lowercase = [textFieldString lowercaseString];
This is the definition for that function:
- (unichar)characterAtIndex:(NSUInteger)index
A unichar is a c data type, and is not a NSString *. You need to do
unichar currChar = [textFieldString characterAtIndex:0];
The message you're getting is due to it trying to cast the integer value of the unichar to a pointer value.
EDIT:
BTW, if you really need a NSString back from that the easiest way would probably be (dry-code):
NSString *currChar = [textFieldString substringWithRange:NSMakeRange(0,1)];
精彩评论