简体   繁体   English

NSDictionary和EXC_BAD_ACCESS

[英]NSDictionary and EXC_BAD_ACCESS

Tried to find the answer here and eventually found a clue on another site. 试图在这里找到答案,并最终找到另一个网站的线索。 Posting here in case anyone searches here and has the same problem. 如果有人在这里搜索并且有相同的问题,请在此处发布。

NSDictionary *d = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"foo", YES, 42, nil] 
forKeys:[NSArray arrayWithObjects:@"bar", @"baz", @"count", nil]];

This produces: 这会产生:

Program received signal: "EXC_BAD_ACCESS"

What is the cause of this? 这是什么原因?

YES and 42 are not object pointers. YES42不是对象指针。 You're trying to create an NSArray, which can only contain objects, and you're passing in values that are not pointers to objects. 您正在尝试创建一个NSArray,它只能包含对象,并且您传入的值不是指向对象的指针。 You'll crash for the same reason that 你会因为同样的原因而崩溃

[YES description];

will crash -- YES is not a valid object pointer. 将崩溃 - YES不是有效的对象指针。

For one thing, in your array, YES and 42 are not objects. 首先,在您的数组中,YES和42不是对象。 Try using [NSNumber numberWithInt:42] there. 尝试在那里使用[NSNumber numberWithInt:42]。 You should have got a compiler warning there. 你应该有一个编译器警告。

A int nor a BOOL are objects and therefore cannot be part of a NSDictionary. int或BOOL是对象,因此不能成为NSDictionary的一部分。 Instead of using int's and bools use their object equivalent of a NSNumber. 而不是使用int和bools使用他们的对象相当于NSNumber。 You can easily store a int using: 您可以使用以下方法轻松存储int:

[NSNumber numberWithInt:(int)]

You can store a BOOL with: 您可以存储BOOL:

[NSNumber numberWithBool:(BOOL)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM