2011-10-09 74 views
0

我用下面的代碼:分配錯誤NSString?

for (int i=1; i<=3;i++){ 
    NSString *theString = [[NSString alloc] initWithFormat:@"%i",imageValue]; 
    theString = [theString stringByAppendingFormat:@"%i.jpg",i]; 
    [img addObject:theString]; 
    NSLog(@"the string %@:",theString); //01.jpg ,02.jpg and 03.jpg 
    [theString release]; 
} 

,但我得到這個錯誤3次,爲什麼?

錯誤:

myapp(15467,0xacdaa2c0) malloc: *** error for object 0x4eb1ca0: pointer being freed was not allocated 

回答

1

stringByAppendingFormat返回一個新字符串,會被自動釋放。這意味着你正在釋放一個自動釋放的對象,這就是爲什麼你得到錯誤,並且你正在泄漏第一行分配的字符串。我建議將第一行更改爲

NSString* theString = [NSString stringWithFormat:@"%i", imageValue]; 

然後完全刪除發行版。

1

嘗試

NSString *theString = [[NSString alloc] initWithFormat:@"%i%i.jpg",imageValue,i]; 

和除去

theString = [theString stringByAppendingFormat:@"%i.jpg",i]; 
1

在聲明循環中的指針theString內側的第一串和分配一個對象:

NSString *theString = [[NSString alloc] initWithFormat:@"%i",imageValue]; 

在第二行你將指針theString重定向到新分配的autore租用字符串[theString stringByAppendingFormat:@"%i.jpg",i];,因此以前分配的對象丟失。這是內存泄漏。

最後,您釋放自動釋放的sting [theString release];,當autorelease循環嘗試再次釋放對象時,它將釋放對象並使應用程序崩潰。

Solient:請閱讀edsko的答案。