Obj-C - NSString to int
I'm making this function that takes a string input, converts it to an int, and finds the binary equivalent. It was working an hour ago, but after i tried tinkering with a different keypad, and then going back, it no longer works:
- (void)convertToBinary:(NSString *)tf
{
NSString *result = @"";
NSLog(@"-- %@", tf); //successfully prints
[tf retain];
if ([tf isKindOfClass:[NSString class]]){
NSLog(@"tf is NSString"); //THIS PRINTS SO TF IS CONFIRMED TO BE NSSTRING
}
int dec = [tf intValue]; //BREAKS HERE...!
if (!dec){
[binaryOutput setText:@"Sorry, invalid input!"];
} else {
...
}
}
I know that to convert an NSString to an int, i just need to do int dec = [someString intValue]
yet that isn't working. The error i'm getting is EXEC_BAD_ACCESS
Any help please?
EDIT
I just made a small command-line project:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool all开发者_JAVA百科oc] init];
// insert code here...
NSString *t = @"123";
int d = [t intValue];
NSLog(@"Hello, %@", d);
[pool drain];
return 0;
}
and the EXEC_BAD_ACCESS still persists for such a simple program! What's the problem here?
You should be using "%d" when printing integers. Change the line to:
NSLog(@"Hello, %d", d);
EXEC_BAD_ACCESS
usually fires when there is a memory leak, check that tf is not null or released.
You can write NSLog(@"%@", tf);
at the beginning of the method to check that.
As edo42 it's probably related to a null/released string. See "EXC_BAD_ACCESS signal received" for lots of information about that error message, and how to debug using NSZombieEnabled.
Instruments.app with the Zombies instrument might help to uncover the crash. Also try a "Build and Analyze" run.
精彩评论