2011-01-27 51 views
0

Im使用字典來保存一些值爲「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); 

} 

我第一次調用這個函數一切正常,它會創建字典並在最後一行中打印「數組」。但是當我再次輸入這個函數時,它會崩潰而沒有錯誤。

我不知道什麼可能會發生......

我解決了崩潰做:

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

我解決了如何添加多個點:

//到viewDidLoad中

Mypoints = [[NSMutableDictionary alloc] init]; 

//進入MYFUNC

[Mypoints setObject:one forKey:key]; 

回答

2

我的點沒有被保留。所以第一次它將是零,第二次Mypoints將指向已釋放的內存。在此代碼

其他小問題:

  1. Mypoints應設置爲無使用前(我想這是在其他地方完成)。
  2. Mypoints = [NSDictionary dictionaryWithObject:one forKey:key];您的字典也將只包含1個鍵/值對,因爲您每次都創建一個新的字典。 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 2011-01-27 08:39:03

1

因爲[NSDictionary dictionaryWithObject:one forKey:key]會返回一個自動釋放對象,該對象在調用-myfunc:之間的某個時間釋放。 NSLog()在第一行顯然發生了崩潰。

+0

我怎樣才能解決呢? – HispaJavi 2011-01-27 09:08:58