简体   繁体   English

NSMutableArray初始化行为

[英]NSMutableArray initialization behavior

When I initialize 当我初始化

self.nsmutableArray = [NSMutableArray array];

in my viewDidLoad method NSMutableArray initialize correctly and i can addObject inside it. 在我的viewDidLoad方法中NSMutableArray正确初始化,我可以在其中添加对象。 But if i skip the above initialization in viewDidLoad method and initialize it in some other methods, NSMutableArray initialize incorrectly and i can not addObject inside it. 但是,如果我在viewDidLoad方法中跳过上述初始化,而在其他方法中对其进行了初始化,则NSMutableArray初始化不正确,并且我无法在其中添加addObject。 Why this behavior. 为什么会这样。 Is it need to be initialized in viewDidLoad always? 是否需要始终在viewDidLoad中初始化它?

I think this is almost a duplicate question. 我认为这几乎是一个重复的问题。 Your issue has little to do with the NSMutableArray initialization and more to do with how you conduct memory management in Objective-C on subclasses of NSObject in general. 通常,您的问题与NSMutableArray初始化无关,而与您如何在Objective-C中对NSObject子类进行内存管理有关。

See related post on NSString s here . 此处查看有关NSString的相关文章。 Look at the top answer. 看最上面的答案。

If you want the array to last for the lifetime of the class, try: 如果您希望数组在类的整个生命周期中持续存在,请尝试:
self.nsmutablearray = [[NSMutableArray alloc] init];

Just make sure you release it in the dealloc method: 只要确保您在dealloc方法中将其释放即可:
[self.nsmutablearray release];

Alternatively, you could @synthesize nsmutablearray, but you would still need to handle its release. 另外,您可以@synthesize nsmutablearray,但是您仍然需要处理其释放。 There are a myriad of ways to address this issue. 有多种方法可以解决此问题。

You don't need to initialize a NSMutableArray in your viewDidLoad message. 您无需在viewDidLoad消息中初始化NSMutableArray。 In fact your NSMutableArray has no knowledge of the context in which it is being initialized. 实际上,您的NSMutableArray不了解对其进行初始化的上下文。

I would investigate the specifics of the problems you are having when you try to subsequently add objects to the array. 当您尝试随后将对象添加到数组时,我将调查您遇到的问题的细节。

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

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