崩溃NSMutableDictionary的setObject函数

时间:2011-12-27 12:58:56

标签: objective-c ios crash

这是我的代码:

NSLog(@"dictionaryPlayers=%@,%d",[dictionaryPlayers description],dictionaryPlayers.count);
[dictionaryPlayers setObject:@"test" forKey:@"test2"];

dictionaryPlayers包含在这个类的init函数中:

-(id)init{
  ...
  dictionaryPlayers = [[NSMutableDictionary dictionaryWithCapacity:10]retain];
  ...
}

程序崩溃了:

Thread 1:Program received signal: "SIGABRT".

在控制台中:

2011-12-27 17:01:21.744 [25454:207] dictionaryPlayers={
},0
2011-12-27 17:01:21.745 [25454:207] -[__NSCFConstantString tick]: unrecognized selector sent to instance 0x199bcc

使用NSLog输出,我认为dictionaryPlayers很好。所以我不知道为什么会崩溃...

4 个答案:

答案 0 :(得分:2)

您调用tick的对象:在内存中不再存在并导致此崩溃。试着了解为什么要释放这个对象。

答案 1 :(得分:0)

这似乎不是本地案例,所以你确定在顶部合成它吗?并在标题中正确声明了吗?例子: 在标题中:

@property (nonatomic, strong) NSMutableDictionary *dictionaryPlayers;
课堂上的

@synthesize dictionaryPlayers = _dictionaryPlayers;

答案 2 :(得分:0)

您不需要在init语句中对对象调用retain。也只是为了咯咯地笑:

dictionaryPlayers = [[NSMutableDictionary alloc] init];

而不是

dictionaryPlayers = [NSMutableDictionary dictionaryWithCapacity:10];

在日志语句上方执行此操作(将其从init中取出)。

如果这样可行,请在您的init方法中输入一个日志,并确保在将KV添加到字典的方法之前调用该方法

我无法重现此行为。这是我的代码: ViewController.h:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property(nonatomic, retain) NSMutableDictionary *dictionaryPlayers;
@property (retain, nonatomic) IBOutlet UITextView *logTextView;
- (IBAction)logButtonPressed:(id)sender;
@end

ViewController.m:

#import "ViewController.h"

@implementation ViewController
@synthesize dictionaryPlayers;
@synthesize logTextView;


#pragma mark - My Methods
- (IBAction)logButtonPressed:(id)sender {
    logTextView.text = [NSString stringWithFormat:@"%@,%d",[dictionaryPlayers description],[dictionaryPlayers count]];
    NSLog(@"dictionaryPlayers=%@,%d",[dictionaryPlayers description],[dictionaryPlayers count]);
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    dictionaryPlayers = [[NSMutableDictionary alloc] init];


    [dictionaryPlayers setValue:@"Test" forKey:@"testKey"];
    NSLog(@"dictionaryPlayers=%@,%d",[dictionaryPlayers description],[dictionaryPlayers count]);
}

没问题。如果你这样做,你就不会有问题。以下是我将进一步排除故障的步骤:

  1. 执行项目搜索playerDictionary,并确保没有其他东西触及该对象。
  2. 尝试清理项目
  3. 使用此结构创建一个新项目,看看会发生什么

答案 3 :(得分:0)

我删除了

dictionaryPlayers = [NSMutableDictionary dictionaryWithCapacity:10]; 

来自init(),并添加了

dictionaryPlayers = [[NSMutableDictionary alloc] init];

在我的日志声明之上。还是崩溃...... 然后我删除了

[dicTest setValue:@"Test" forKey:@"testKey"];

所以只剩下两行:

dictionaryPlayers = [[NSMutableDictionary alloc] init];
NSLog(@"dictionaryPlayers=%@,%d",[dictionaryPlayers description],dictionaryPlayers.count);

它没有崩溃。所以,似乎setValue行确实是问题所在。