2011-01-27 83 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