I am making a fraction calculator app from the Programming In Objective-C 2.0 book. I am using XCode 4.1 for Lion. I have completely and successfully without any error typed in the code. But when I press a number button while the app is running, the label doesn’t input any text. When I press a number button, it should find the UIButton senders tag (which I have allocated)
-(IBAction)clickDigit:(UIButton *)sender {
int digit = sender.tag;
[self processDigit:digit];
}
and it gets sent to this code:
-(void)processDigit:(int)digit {
currentNumber = currentNumber * 10 + digit;
[displayString appendString:[NSString stringWithFormat:@"%i", digit]];
display.text = displayString;
NSLog(@"Processed");
}
The console DOES print Processed. Indicating that this button is working, so the problem lies in this line of code:
[displayString appendString:[NSString stringWithFormat:@"%i", digit]];
display.text = displayString;
display is a UILabel, it is an instance variable but it is not an IBOutlet but is declared as an IBOutlet in its property.
@property (nonatomic, retain)IBOutlet UILabel *display;
I have connected the label on the .xib screen using the connection to code assistant thing. I can literally connect it to the declarations. So I connected it to the property.
Now, the problem lies in the fact that display is a UILabel and its text property requires an NSString not a NSMutableString right? But an NSString cannot append a string and many other methods that I need it to do for this app. How can I make this work?
NSMutableStringandNSStringare mostly interchangeable. I.e. if a method requires anNSString, you can pass it anNSMutableString. This doesn’t work the other way, though, and they are often copied and made immutable. i.e. even if you pass anNSMutableStringtoUILabel‘stextproperty, it will always return anNSStringback.I suspect you’ve got some other issue going on here.
That said, it’s often easier to work with immutable strings than mutable ones.
You can change this code:
into this code:
Because
stringByAppendingStringmakes a new immutable string object with the contents of the receiver (displayString) and the string passed as a parameter ([NSString stringWithFormat:@"%i",digit]).I suspect your issue is
displayStringisnil.Add some NSLog’s to find out…
-(IBAction)clickDigit:(UIButton *)senderaddNSLog(@"Sender is %@",sender)-(void)processDigit:(int)digitaddNSLog(@"Digit is %i and displayString is %@ and display is %@", digit, displayString, display);This should give you an idea of what objects are nil, or badly connected in Interface Builder.