iphone - NSMutableDictionary 向 objectForKey 抛出 doesNotRecognizeSelector 吗?

标签 iphone objective-c nsmutabledictionary custom-view

我对 iPhone 编程完全是个菜鸟,而且我遇到过抛出异常的情况,但我无法理解。

背景:错误发生在自定义 subview 中,并且在加载程序后立即发生。我在重写的drawRect方法中抛出异常。抛出错误的代码如下:

- (void)drawRect:(CGRect)rect{
    NSNumber *points = [NSNumber numberWithInt: star.numberOfPoints];
    //HERE. Doesn't recognize selector?!
    CGPathRef t = (CGPathRef)[starPaths objectForKey:points];
 /*snip*/

starPaths 在 awakeFromNib 中初始化为容量为 1 的 NSMutableDictionary。

抛出的异常是 -[NSObject doesNotRecognizeSelector:]

starPaths 在 View 的头文件中声明为

    NSMutableDictionary *starPaths;

并初始化为

- (void)awakeFromNib{
    starPaths = [NSMutableDictionary dictionaryWithCapacity: 1];
} 

最后,我无法在代码中成功地将元素添加到字典中,因为添加条目的代码依赖于从字典接收零响应来知道该特定元素需要构建条目。

有什么建议吗?我还需要提供其他信息吗? 任何帮助都将不胜感激,我觉得我错过了一些明显的东西,但我一整天都在为此苦苦挣扎,但没有运气。

最佳答案

如果您不保留 starPaths 变量或使用 [[NSMutableDictionary alloc] initWithCapacity:1] 自己显式分配它,那么它将在运行循环的下一次迭代时自动释放。

你需要做

starPaths = [[NSMutableDictionary dictionaryWithCapacity:1] retain];

或者

starPaths = [[NSMutableDictionary alloc] initWithCapacity:1];

只要确保在不再需要时释放它即可。

关于iphone - NSMutableDictionary 向 objectForKey 抛出 doesNotRecognizeSelector 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1067494/

相关文章:

objective-c - 使用 NSIndexPath 作为 NSMutableDictionary 中的键的问题?

iphone - 插入命令错误 - Appcelerator Titanium

iphone - 灰色 UISearchBar 以编程方式匹配范围栏

ios - 如何在 Grand Central Dispatch 中创建死锁?

ios - swift 中的函数指针

ios - iOS:从字典获取数组中的值

iOS 不兼容的指针类型(NSDictionary 中的 NSMutableDictionary)

iphone - 更改 UIView 中的坐标原点

iphone - 返回主屏幕

iphone - 将 UILabel 添加到 UIImageView