Question

I would need some expert advice on how to solve this problem. I am doing some crude testing for a new app for the iPad.

I create a NSMutableArray (ballPath) in the viewDidLoad of my view controller (it is declared in my .h file) by loading a plist file created in another app.

ballPath = [[NSMutableArray alloc] initWithCapacity:1000];

NSString *path=[[NSBundle mainBundle] pathForResource:@"level_1" ofType:@"plist"];

ballPath = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

This array now contains a number of CGPoints (stored by the other app as NSValues and the archived).

enter image description here

I then draw the path (still in my viewDidLoad), which works fine, so the path should work fine.

When I later on want to read the array as a response to changes in acceleration, I get an EXC_BAD_ACCESS. When I debug and look at my array it looks like this:

enter image description here

I test and replace the loaded array with this (also in viewDidLoad):

    ballPath = [[NSMutableArray alloc] initWithObjects:
            [NSValue valueWithCGPoint:CGPointMake(100.0, 100.0)],
            [NSValue valueWithCGPoint:CGPointMake(100.0, 200.0)],
            [NSValue valueWithCGPoint:CGPointMake(100.0, 300.0)],
            [NSValue valueWithCGPoint:CGPointMake(100.0, 400.0)],
            [NSValue valueWithCGPoint:CGPointMake(125.0, 450.0)],
            [NSValue valueWithCGPoint:CGPointMake(150.0, 500.0)],
            [NSValue valueWithCGPoint:CGPointMake(300.0, 600.0)],
            [NSValue valueWithCGPoint:CGPointMake(350.0, 550.0)],nil];

Then it works just fine!

enter image description here

What am I missing here????

I'm on Xcode 4.0.2 and my target is iOS 4.3.

Was it helpful?

Solution

The array is deallocated at that point, so that there's some random memory where the array previously was.

unarchiveObjectWithFile: returns an autoreleased object, if you want to keep the array around, you need to retain it (or make it a retained property). The alloc-init two lines earlier is completely superfluous (and probably leaks memory), because you're never doing anything with the array you create there, it is replaced by the array you load from the bundle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top