2013-02-12 120 views
0

我正在使用XCode開發iPhone應用程序。我是這個平臺的新手,需要一些特定的問題的幫助...NSMutableArray發佈導致崩潰

我有一個方法,處理一些數據並返回兩個整數值作爲NSNumber包裝成一個NSMutableArray。

這裏是方法:

-(NSMutableArray *)processPoints:(int) x:(int) y 
{ 
NSMutableArray *mutArray = [[NSMutableArray alloc] initWithCapacity:3]; 
int x9,y9; 

// ...do some processing... 

NSNumber* xNum = [NSNumber numberWithInt:x9]; 
NSNumber* yNum = [NSNumber numberWithInt:y9]; 

[mutArray addObject:xNum]; 
[mutArray addObject:yNum]; 

    return [mutArray autorelease]; 
} 

我調用上述方法從另一種方法,其中I的NSNumber的東西複製到局部變量,然後釋放NSMutable陣列的本地副本。

但是,當釋放這個NSMutable數組(變量'mutArray')時,應用程序崩潰。

這裏是方法:

-(void)doNinjaAction 
{ 
    NSMutableArray* mutArray = [self processPoints: x :y]; 

    NSNumber* s1 = [[mutArray objectAtIndex:0] retain]; 
    NSNumber* s2 = [[mutArray objectAtIndex:1] retain]; 

    x = [s1 integerValue]; 
    y = [s2 integerValue]; 

    //...proceed with other stuff... 

    [mutArray autorelease]; //this is where the system crashes. same for 'release'    
          //instead of 'autorelease' 
    } 

能否請你解釋一下,我正與內存釋放的過程中走錯了。

我對這個過程的理解有點不穩定。請幫忙。

+0

它正在崩潰,因爲你自動釋放它兩次。 – 2013-02-12 06:32:34

回答

1

當你調用語句

NSMutableArray* mutArray = [self processPoints: x :y]; 

這本身充當自動釋放。

因此,明確釋放數組會導致應用程序崩潰。

+0

明白了......謝謝。 – metsburg 2013-02-12 07:01:53

0

您正在釋放mutArray多次。一旦進入processPoints功能並再次進入doNinjaAction

要解決的崩潰刪除:

[mutArray autorelease]; 
+0

「試着在那裏打印保留數,這樣你就會明白它出錯的地方了」 - [如果他這樣做,他會更加困惑。](http://whentouseretaincount.com) – 2013-02-12 06:23:03

+0

@ H2CO3:同意。將編輯答案。謝謝。 – Rushi 2013-02-12 06:25:43

+0

不客氣。請分享這個鏈接與誰想給這個建議:) – 2013-02-12 06:27:59

2

因爲你overreleasing數組。你分配 - 在processPoints:初始化它,然後你autorelease它 - 這是正確的,這是你如何處置它的所有權。

之後,你不需要,也不一定自動釋放或再次釋放它。這不是標準庫中的malloc()

+0

是的,現在我明白了。謝謝。 – metsburg 2013-02-12 07:02:28

0
-(NSMutableArray *)processPoints:(int) x:(int) y 
{ 
NSMutableArray *mutArray = [[NSMutableArray alloc] initWithCapacity:3]; 
int x9,y9; 

// ...do some processing... 

NSNumber* xNum = [NSNumber numberWithInt:x9]; 
NSNumber* yNum = [NSNumber numberWithInt:y9]; 

[mutArray addObject:xNum]; 
[mutArray addObject:yNum]; 

[mutArray autorelase]; 
    return mutArray; 
} 

試試這一個它會解決它。

+0

是的....第二次沒有釋放它也工作正常。非常感謝。 – metsburg 2013-02-12 07:05:34

-1

由於@ H2CO3和@AppleDelegate建議,它是正確的。

不過我會建議使用ARC並將您的項目轉換爲ARC啓用。

轉到編輯 - > Refactor->轉換爲Objectiv-C ARC

然後你不需要做任何版本的任何地方。它會照顧到所有的版本:)

+0

誰投了負面可能我知道男人?給我理由 – Bhupendra 2013-02-12 08:00:31

+0

僅供參考...我試圖給你投票...但我不允許... :( – metsburg 2013-02-13 11:25:50

0
-(NSMutableArray *)processPoints:(int) x:(int) y 
{ 
NSMutableArray *mutArray =[[[NSMutableArray alloc] initWithCapacity:3]autorelease]; 
int x9,y9; 

// ...do some processing... 

NSNumber* xNum = [NSNumber numberWithInt:x9]; 
NSNumber* yNum = [NSNumber numberWithInt:y9]; 

[mutArray addObject:xNum]; 
[mutArray addObject:yNum]; 

    return mutArray; 
}