objective-c NSMutableArray addObject 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1827058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:34:22  来源:igfitidea点击:

NSMutableArray addObject not working

objective-cnsmutablearray

提问by joec

I have declared an NSMutableArray *categoriesin my view controller .h file, and declared a property for it.

我已经NSMutableArray *categories在我的视图控制器 .h 文件中声明了一个,并为其声明了一个属性。

In the parser:foundCharacters:method of the NSXMLParserdelegate in my .m file, I have this code:

在我的 .m 文件parser:foundCharacters:中的NSXMLParser委托方法中,我有以下代码:

-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string  
{  
    if (elementFound)  
    {  
        element = string;  
        [self.categories addObject:element];  
    }  
}

But when I hover over the [self.categories addObject:element]line after stepping into it in debug mode, XCode tells me the size is 0x0, 0 objects. There are 3 elements in my XML file so 3 items should be in the array.

但是当我[self.categories addObject:element]在调试模式下进入该行后将鼠标悬停在该行上时,XCode 告诉我大小为 0x0, 0 个对象。我的 XML 文件中有 3 个元素,因此数组中应该有 3 个项目。

I'm missing something really obvious and I can't figure out what.

我错过了一些非常明显的东西,我无法弄清楚是什么。

回答by Joshua Nozzi

The "0x0" part is a memory address. Specifically, "nil", which means your mutable array doesn't exist at the time this is being called. Try creating it in your -init method:

“0x0”部分是内存地址。具体来说,“nil”,这意味着您的可变数组在调用时不存在。尝试在您的 -init 方法中创建它:

categories = [[NSMutableArray alloc] init];

Don't forget to release it in your -dealloc.

不要忘记在您的 -dealloc 中释放它。

回答by Vishal16

Initialize an empty array using

使用初始化一个空数组

categories = [NSMutableArray array];

The array class method are autoreleased so no need to release.

数组类方法是自动释放的,所以不需要释放。