Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSstring with format error in IBAction

I have declared NSString with some string value in ViewdidLoad like..

int i=1;
strval=[NSString stringWithFormat:@"%03d",i];
strval=[NSString stringWithFormat:@"S%@",strval];

NSLog(@"Value %@",strval);

it gives correct result as S001, but when i print this same in IBAction like,

- (IBAction)stringvalue:(id)sender {
NSLog(@"Value %@",strval);
}

it gives unknown values each time.Sometimes it throws EXEC_BAD_ACCESS error.

Please help me..

like image 800
Harish Avatar asked Mar 30 '26 15:03

Harish


2 Answers

Try something like this

in .h

  @property (nonatomic, strong) NSString *strval;

in .m

  @synthesize strval = _strval

  - (void)viewDidLoad 
  {
      int i = 4;
      // ARC
      _strval = [NSString stringWithFormat:@"hello %d", i];
      // None ARC
      // strcal = [[NSString alloc] initwithFormat:@"hello %d",i];
      NSLog(@"%@", _strval);
      // Prints "hello 4" in console (TESTED)
  } 

  - (IBAction)buttonPress:(id)sender
  {
      NSLog(@"%@", _strval);
      // Prints "hello 4" in console (TESTED)
  }

using ARC. This has been tested and works the way the question has been asked.

like image 111
Popeye Avatar answered Apr 02 '26 12:04

Popeye


Looks like you aren't using ARC, so the string is being released the next time the autorelease pool drains. You need to explicitly retain it in viewDidLoad and explicitly release it in your overwridden dealloc method:

- (void)viewDidLoad
{
    ...

    strval = [[NSString stringWithFormat:@"%03d", i] retain];

    ....
}

- (void)dealloc
{
    [strval release];

    ...

    [super dealloc];
}

(I am assuming you've actually declared strval as an instance method).

like image 24
trojanfoe Avatar answered Apr 02 '26 13:04

trojanfoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!