NSArray 随机变成不同的东西!

发布于 2024-09-13 21:23:02 字数 345 浏览 5 评论 0原文

我认为我的内存管理有问题。我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

抱着落日 2024-09-20 21:23:02

发生的情况是,内存一旦被 NSArray 占用,就会被另一个对象占用。这可以是任何对象,并且由于您经常触摸屏幕,因此 UITouch 很常见。

这意味着您没有在应该保留 NSArray 的时候保留它,因此它会被过早释放。您没有显示声明 arr 的代码,但如果您将 arr 声明为

@property (nonatomic,retain) NSArray *arr;

并使用合成它,

@synthesize arr;

则通过简单地分配给 self.arr 而不是 来处理保留>arr

self.arr = [input componentsSeperatedByString:@"\n"];

用可可语言来说,您的对象现在“拥有”该数组。在此类的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 as

@property (nonatomic,retain) NSArray *arr;

and synthesize it using

@synthesize arr;

then the retaining is handled by simply assiging to self.arr instead of arr:

self.arr = [input componentsSeperatedByString:@"\n"];

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 to self.arr previously will get released, and the new one retained.

小鸟爱天空丶 2024-09-20 21:23:02

尝试保留arr

arr = [[input componentsSeperatedByString:@"\n"] retain];

Try to retain arr.

arr = [[input componentsSeperatedByString:@"\n"] retain];
桃气十足 2024-09-20 21:23:02

或者用这个数组初始化一个新数组:

arr = [[NSArray alloc] initWithArray:input];

Or Initalize a new Array with this array:

arr = [[NSArray alloc] initWithArray:input];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文