user1123599
user1123599

Reputation:

Runtime error when NSString Object is released

In my Function below if I remove the tempString release statement it works just fine but with it, there is ALWAYS a runtime error. It is a simple function that displays an array in an NSTextField either _stackDisp1 or _stackDisp2 but for some reason releasing the string creates a runtime error Any help?

- (void) displayArr:(NSMutableArray*)stack{
  NSTextField *myObj;
  if([stack count] <= 10) myObj = _stackDisp1;
  else myObj = _stackDisp2;
  NSString *tempString = [[NSString alloc]initWithString:@""];
  for(NSString *i in stack){
    tempString = [NSString stringWithFormat:@"%@\n%@",tempString,i];
  }
  [myObj setStringValue:tempString];
  [tempString release];
}

Upvotes: 1

Views: 72

Answers (2)

IlDan
IlDan

Reputation: 6869

That's because

tempString = [NSString stringWithFormat:@"%@\n%@",tempString,i];

creates a new autoreleased object assigning it to your variable tempString. The pointer to the first object gets lost and you end up over-releasing an autoreleased object. Just change the initial assignment to

  NSString *tempString = @"";

and remove the [tempString release] line.

Upvotes: 1

Regexident
Regexident

Reputation: 29552

In the for loop you're assigning tempString to an autoreleased string:

tempString = [NSString stringWithFormat:@"%@\n%@",tempString,i];

releasing it manually results in a BAD_ACCESS.

Also you are probably looking for this:

- (void) displayArr:(NSMutableArray*)stack{
  NSTextField *myObj = ([stack count] <= 10) ? _stackDisp1 : _stackDisp2;
  [myObj setStringValue:[stack componentsJoinedByString:@"\n"]];
}

The declaration/assignment of myObj was a bit too verbose for my taste,
so I used a ternary operator instead (it's use is not essiential though. Just a matter of style.).

Upvotes: 0

Related Questions