NSArray 随机变成不同的东西!
我认为我的内存管理有问题。我的 NSArray(称为 arr)在随机时间变成不同的东西。我不知道为什么。我有一个声明数组的 .h 文件,然后使用初始化数组
NSString *input = [[NSString alloc] initWithData:myData encoding:NSACIIStringEncoding];
arr = [input componentsSeperatedByString:@"\n"];
,然后在整个程序中使用它,突然它会变成不同的东西(例如,有时是 UITouch)。我从来没有发布过它。它为什么要这样做?如何防止对象因内存问题而随机更改?
谢谢!
I am having a problem with memory management I think. My NSArray (called arr) is turning into different things at random times. I have no idea why. I have a .h file that that declares the array, and then I initialize the array using
NSString *input = [[NSString alloc] initWithData:myData encoding:NSACIIStringEncoding];
arr = [input componentsSeperatedByString:@"\n"];
and then I use it throughout the program and suddenly it changes into different things (UITouch, sometimes, for example). I never called a release on it. Why is it doing this? How do I prevent objects from randomly being changed due to memory issues?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
发生的情况是,内存一旦被 NSArray 占用,就会被另一个对象占用。这可以是任何对象,并且由于您经常触摸屏幕,因此 UITouch 很常见。
这意味着您没有在应该保留 NSArray 的时候保留它,因此它会被过早释放。您没有显示声明
arr
的代码,但如果您将 arr 声明为并使用合成它,
则通过简单地分配给
self.arr
而不是来处理保留>arr
:用可可语言来说,您的对象现在“拥有”该数组。在此类的
dealloc
方法中,您应该[self.arr release]
。如果您将其他数组分配给
self.arr
,则先前分配给self.arr
的对象将被释放,并保留新的对象。What happens, is that the memory, once occupied by your NSArray, is occupied by another object. This may be any object, and since you're touching the screen a lot a UITouch is very common.
This means you're not retaining the NSArray when you should, so it is released prematurely. You don't show the code declaring
arr
, but if you declare arr asand synthesize it using
then the retaining is handled by simply assiging to
self.arr
instead ofarr
:In cocoa-speak, your object now "owns" the array. In the
dealloc
method of this class, you should[self.arr release]
.Should you assign some other array to
self.arr
, the object assigned toself.arr
previously will get released, and the new one retained.尝试保留arr。
Try to retain arr.
或者用这个数组初始化一个新数组:
Or Initalize a new Array with this array: