views:

98

answers:

3

Hi,

I'm a complete novice, so I'm probably missing something really easy, but I can't get my string appending to work. I add the 3rd character to typedDigit & it crashes - the method is called fine and typedDigit will get to 2 characters long. I think everything is declared properly in the header file. Code is -

-(IBAction)digitPressed:(UIButton *)sender {

    NSString *digit = [[sender titleLabel] text]; // in this case, "0" - "9"

    if (userIsInMiddleOfTyping) {   // typedDigit is already at least 1 character long
        typedDigit = [typedDigit stringByAppendingString:digit];
    } else {                        // first character of typedDigit
        typedDigit = digit;
        userIsInMiddleOfTyping = YES;
    }

}

Many thanks for any help!

A: 

You'll want to make sure digit is not NULL when trying to appending it. Also there is no mention of typedDigit's initialization, so if it is a garbage pointer or otherwise poorly-initialized, you'll crash when you try to manipulate it.

fbrereto
A null `typedDigit` is unlikely to be a problem, as messages to null objects are silently discarded in Objective C.
Adam Wright
+1  A: 

Without the stack trace of the crash, it's hard to know the cause, but my guess will be that typedDigit is being autoreleased before the next call of your digitPressed function. stringByAppendingString: returns an autoreleased object, so you'll need to retain it if you want it to hand around past the next autorelease pool flush. For a direct fix, try something like...

if (userIsInMiddleOfTyping) {
  typedDigit = [[[typedDigit autorelease] stringByAppendingString:digit] retain];
} else {  
  typedDigit = [digit retain];
  ...

More than this, you'll need to make sure you release typedDigit at some point after the typing is over, and you're finished with it.

Adam Wright
Franklyn Weber
A: 

I think you probably have an ownership problem. If typeDigit is an object instance variable, you should be setting it with a setter method. In any case, you never call "retain" on the strings you want to keep around, so they are probably deallocated behind your back between method calls.

darren