开发者

NSMutableString help Objective C

开发者 https://www.devze.com 2023-02-22 03:39 出处:网络
I currently have the following code: -(void) inputNumber:(int)number { NSString *str; str = [NSString stringWithFormat:@\"%d\", number];

I currently have the following code:

-(void) inputNumber:(int)number {

    NSString *str;

    str = [NSString stringWithFormat:@"%d", number];
    [strVal appendStri开发者_StackOverflow中文版ng:str];
    txtShowNum.text = strVal;
}

I have already defined NSMutableString *strVal; before in my code.

When the function above executes the field remains blank, but if i were to use:

txtShowNum.text = str;

I get the value that I'm meant to but I obviously need the value concatenated.

Can anyone shed some light on this.

Thanks


You should allocate an NSMutableString as well in your code, somewhere before this method is called.

E.g. like this:

-(void) inputNumber:(int)number {
    if ( strVal == nil ) strVal = [[NSMutableString alloc] init];
    NSString *str = [NSString stringWithFormat:@"%d", number];
    [strVal appendString:str];
    txtShowNum.text = strVal;
}

There are however some memory issues here. You'd better make strVal a retained property and then do:

    if ( self.strVal == nil ) self.strVal = [NSMutableString string];


Your strVal is most probably nil, so you call appendString: on nil which essentially does nothing at all, and setting the text field to nil will erase its contents.


If you just declared it as a member variable, make sure you initialize it somewhere:

NSMutableString* strVal = @"";

If not, you are just calling a method on a nil object.

0

精彩评论

暂无评论...
验证码 换一张
取 消