2011-01-27 11 views
0

辞書を使用して値 "1"の位置を保存しています。NSDictionaryを使用したクラッシュエラー - Iphone SDK

/* * * header * * */ 

NSDictionary *Mypoints; 

/* * * * * * * * */ 

-(void)myfunc: (float)y :(float)x{ 

    NSLog(@"%@",Mypoints); 

    NSNumber *one = [NSNumber numberWithInt:1]; 
    NSString *key = [[NSString alloc] initWithFormat:@"%f,%f",y,x]; 

    [Mypoints setObject:one forKey:key]; 

    //show the value 
    NSNumber *tempNum = [Mypoints objectForKey:key]; 
    int i = tempNum.intValue; 
    NSLog(@"Value: %i",i); 

    //print all 
    NSLog(@"%@",Mypoints); 

} 

私は、この関数のすべてが大丈夫です呼び出す最初の時間は、それは辞書を作成し、最後の行の「アレイ」を印刷します。しかし、この関数を再び入力すると、エラーなしでクラッシュします。 viewDidLoadに

//:私はより多くのポイントを追加する方法を解く

Mypoints = [[NSMutableDictionary dictionaryWithObject:one forKey:key]retain]; 

私が起こってすることができるかわからない...

は、私はそれをやってクラッシュを解決しました

Mypoints = [[NSMutableDictionary alloc] init]; 

//てmyfuncに

[Mypoints setObject:one forKey:key]; 

答えて

2

ポイントは保持されません。だから初めてそれは無くなるでしょう、二度目にMypointsは解放された記憶を指しています。このコードで

その他のマイナーな問題:

  1. Mypointsは、使用前にnilに設定する必要があります(私はこれが他の場所で行われていると仮定)。
  2. Mypoints = [NSDictionary dictionaryWithObject:one forKey:key];毎回新しい辞書を作成するため、辞書には1つのキー/値のペアのみが含まれます。
  3. NSString * key = [[NSString alloc] initWithFormat:@ "%f、%f"、y、x];リリースされていないので、これはリークします。

// Not keen on this being a global but whatever... It needs to be initialised somewhere in this example. NSMutableDictionary* Mypoints = nil;

-(void)myfunc: (float)y :(float)x {
// This is hacky but shows the principle. if (Mypoints == nil) { Mypoints = [ NSMutableDictionary alloc ] initWithCapacity: 10 ]; // Or whatever you think the size might be. Don't forget to release it somewhere. }

NSNumber *one = [NSNumber numberWithInt:1]; NSString *key = [NSString stringWithFormat:@"%f,%f",y,x]; // This stops the leak since it is now already autoreleased. [ MyPoints setObject: one forKey: key ]; // Be careful no other key can have the same x and y value. //show the value NSNumber *tempNum = [Mypoints objectForKey:key]; int i = tempNum.intValue; NSLog(@"Value: %i",i); //print all NSLog(@"%@",Mypoints);

}

+0

そして...この機能に入るたびに、どのように "ポイント"を追加できますか? – HispaJavi

+0

あなたはNSMutableDictionaryと - (void)setObjectを使うべきです:(id)anObject forKey:(id)aKey – martinws

+0

私はどこでそれをしなければならないか説明できますか?その辞書がオートレリースされていると言うと、私は関数に入力するたびに空になります?? – HispaJavi

1

[NSDictionary dictionaryWithObject:one forKey:key]は、自動解放オブジェクトを返します。このオブジェクトは、-myfunc:の呼び出しの間に解放されることがあります。明らかにNSLog()の最初の行でクラッシュが発生しています。

+0

どのように私はそれを解決することができますか? – HispaJavi

関連する問題