NSArray randomly turning into different things!
Question
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!
Solution
Try to retain arr.
arr = [[input componentsSeperatedByString:@"\n"] retain];
OTHER TIPS
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.
Or Initalize a new Array with this array:
arr = [[NSArray alloc] initWithArray:input];