I have the following code:
NSString *Items[91];
in the .m file above all the methods to serve as global array which in my init method i do:
for (j1 = 0; j1 <= 90; j1++)
{
Items[j1] = [[NSString alloc] initWithFormat:@""];
}
and at some point a different method AA is triggered and do:
Items[40] = [NSString stringWithFormat:@"40. Pers:%g each", PersExemptions];
Items[41] =@"blah blah";
… etc
and at some point a different method BB is triggered and i see that for Items[40] it says freed object, it’s losing the value it had which defeat the purpose. Grr.
I would like Items array to keep their modified values thru the app until the end and I assumed that using the initWithFormat that i used in the init method should take care of it.
I understand that Items is c-style array (and to convert to NSMutable array would pain) if that’s the problem to begin with.
I appreciate any help on this.
EDIT: As @dasblinkenlight points out, I’m assuming here you are not using ARC.
You’re using a C-style array here, an array of NSString*.
The problem is that when you do this…
[NSString stringWithFormat:@"40. Pers:%g each", PersExemptions]stringWithFormat:returns an NSString that you do not own. If you want to hold onto that NSString in your array, you need to retain it. Or you can use the alloc/initWithString that you did earlier:Items[40] = [[NSString alloc] initWithFormat:@"40. Pers:%g each", PersExemptions];That gives you an NSString that you do own. But of course, that leads to another bug, which is that you just leaked whatever NSString happened to be in Items[40] a moment ago.
So you could make sure to always release the previous string each time, or you can save yourself a lot of effort and just use an NSMutableArray instead. NSMutableArray will take care of retaining each new value and releasing the one that was just replaced. I know you say that’s too much effort, and without looking at your code no one else can say, but accounting for each object you store might actually be more effort.
I hope that helps.