views:

132

answers:

1

Hi,

I'm having a hard time working with arrays. Coming from AS2/AS3 and garbage collection is new to me ... ;)

This is not the full code, just the parts that matter.

.h-file
@interface HelperViewController : UIViewController {
    NSMutableArray *pagesNumbers;
}
@property (nonatomic, retain) NSMutableArray *pagesNumbers;

.m-file
@synthesize pagesNumbers;
-(void)loadView {
    pagesNumbers = [NSMutableArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:1], [NSNumber numberWithInt:1], [NSNumber numberWithInt:1], nil];
    NSLog(@"pagesNumbers: %@", pagesNumbers); // WORKS!
}
-(void)changePage:(id)sender {
    NSLog(@"pagesNumbers: %@", pagesNumbers); // PROBLEM*
}

The PROBLEM* up there is, that it works when the function is called by viewDidLoad, but DOES CRASH when it is called by a UIButton later on with this (very informative) msg:

[Session started at 2009-08-25 11:12:51 +0200.] GNU gdb 6.3.50-20050815 (Apple version gdb-966) (Tue Mar 10 02:43:13 UTC 2009) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-apple-darwin".sharedlibrary apply-load-rules all Attaching to process 13197.

Can anyone help, please?

Regards, Eric.

+2  A: 

Looks like pagesNumbers is not being retained.

Try adding:

[pagesNumbers retain];

after the array has been initialized in loadview.

I believe arrayWithObjects will return an autoreleased array, so you need to explicitly retain it if you want to use it later on.

Edit, just noticed pagesNumbers is also a property. You are initializing pagesNumbers directly so the synthesized setter won't be being called (and not getting automatically retained). If you wanted to use the property setter, I believe you need to reference pagesNumbers using self, ie

self.pagesNumbers = [NSMutableArray arrayWithObjects.....
Tom
Thanks a lot, Tom, the "self" did the trick. And with your explanation it's finally permanently burnt into my brain to use "self". Have a nice day, mine is thanks to you now! ;)
Eric S.