【问题标题】:NSMutableArray containsObject method not detecting objectNSMutableArray containsObject 方法未检测到对象
【发布时间】:2009-08-05 21:23:27
【问题描述】:
// Add the button to the NSMutableArray.
...
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[[self hBtns] addObject:btn];
...

// In another method, try to see if it exists.
- (void)didPushBtn:(id)sender
{
  UIButton *btn = (UIButton *)sender;
  if ([[self hBtns] containsObject:btn]) // Is false every time.
  ...
}

为什么没有检测到 UIButton 在数组中?


编辑

事实证明,它甚至不会在添加后立即检测到它:

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[[self hBtns] addObject:btn];
if ([[self hBtns] containsObject:btn]) // Returns false.

【问题讨论】:

    标签: objective-c iphone nsmutablearray


    【解决方案1】:

    听起来isEqual: 比较失败了。你能看看两个地方的 UIButton 的 hash (添加它的地方,然后在 didPushBtn 中),看看它们的值是否相同?

    【讨论】:

    • 感谢梅雷迪思的帮助。哈希是相同的。关于为什么 isEqual: 比较会失败的任何其他想法?
    • 嘿梅雷迪思,请参阅我对问题的编辑。也许这会有所帮助。
    • 没关系,想通了(见下文)。不过感谢您的帮助,我很感激!
    【解决方案2】:

    我忘记初始化数组(*doh*):

    [self setHBtns:[[NSMutableArray alloc] initWithCapacity:0]];
    

    【讨论】:

    • 这实际上是我的下一个建议。很高兴你把它整理好了。
    • 您还应该确保 setHBtns: 不保留数组,否则您会发生内存泄漏。
    • 要么,要么它应该保留数组,他可以使用[NSMutableArray arrayWithCapacity:0](或只是[NSMutableArray array])代替。我心中更大的问题是属性是否应该是readonly,并且数组应该只在包含类的初始化程序中创建一次。
    • [拍脑袋]。很高兴你分享了问题和答案——同样的问题让我发疯了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多