1

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.

4

2 回答 2

3

编辑:正如@dasblinkenlight 指出的那样,我在这里假设您没有使用ARC。

你在这里使用了一个 C 风格的数组,一个 NSString* 的数组。

问题是当你这样做时......

[NSString stringWithFormat:@"40. Pers:%g each", PersExemptions]

stringWithFormat:返回一个您不拥有的 NSString。如果你想在你的数组中保留那个 NSString,你需要保留它。或者您可以使用之前执行的 alloc/initWithString:

Items[40] = [[NSString alloc] initWithFormat:@"40. Pers:%g each", PersExemptions];

这给了你一个你拥有的 NSString 。但当然,这会导致另一个错误,即您刚刚泄露了 Items[40] 中的任何 NSString。

所以你可以确保每次都释放前一个字符串,或者你可以节省很多精力,只使用 NSMutableArray 代替。NSMutableArray 将负责保留每个新值并释放刚刚替换的值。我知道你说这太费力了,而且不看你的代码没人能说,但考虑到你存储的每个对象实际上可能会费力。

我希望这会有所帮助。

于 2012-08-05T02:04:14.723 回答
0

现在 nsstring 是:

NSString ** strArr;
int rows = 91;

然后,您需要使用 malloc 来动态分配内存:

int i;
strArr = malloc( rows * sizeof( strArr * ) );

for( i = 0; i < rows; i++ )
{
 strArr[ i ] = calloc( columns, sizeof( NSString ) );
}

不要忘记在您的 dealloc 方法中释放:

int i;

for( i = 0; i < rows; i++ )
{
  free( strArr[ i ] );
}
free( strArr);
于 2012-08-05T03:37:36.277 回答