Problem with reinitializing of string in iPhone
I have an interface like this:
@interface MacCalculatorAppDelegate:NSObject
<UIApplicationDelegate> {
// ...
UIButton *operatorPressed;
NSString *waitingOperation;
}
And I am initializing waitingOperation
variable in my implementation like this:
- (id)init {
if (self = [super init]) {
waitingOperation = @"not set";
}
return self;
}
And I want to reinitialize this variable in a function. This is calculator program and when user clicks on operators button the following function will be invoked:
- (IBAction)operatorPressed:(UIButton *)sender {
if([@"+" isEqual:o开发者_开发知识库perand]) {
waitingOperation = @"+";
}
}
But after the check in if
statement, my program won't do anything and this happens when I am trying to reinitialize waitingOperation
variable.
I am new to objective-c
, please help me understand what's wrong here.
Thanks in advance.
There are several things to note here.
waitingOperation=@"not set";
As it stands, this will eventually crash your program. Objective C string literals are autoreleased instances of NSString
, which means unless you assign it to a retained property or retain it manually, the memory will be deallocated, leaving a dangling pointer.
-(IBAction) operatorPressed:(UIButton *)sender {
Have you verified that this method is actually being called? You have to assign the IBAction
in Interface Builder. Step through it in the debugger or use NSLog
to verify that this method is being called.
if([@"+" isEqual:operand])
Where is operand
coming from?
waitingOperation=@"+";
Same problem as above, this will get deallocated behind the scenes, leaving you with a dangling pointer.
Also, note that if you know that both variables are NSString
s, using isEqualToString:
is faster than using isEqual:
.
Finally, this stuff shouldn't be part of your app delegate. This is view controller logic.
If your operand is also a string, then check for isEqualToString
instead of isEqual
精彩评论