views:

53

answers:

2

Hello - in my app, an NSMutableArray is populated with an object in viewDidLoad (eventually there will be many objects but I'm just doing one til I get it working right). I also start a timer that starts a method that needs to access the NSMutableArray every few seconds. The NSMutableArray works fine in viewDidLoad, but as soon as that method is finished, it loses the object.

myApp.h

@interface MyApp : UIViewController {

    NSMutableArray *myMutableArray;
    NSTimer *timer;
}

@property (nonatomic, retain) NSMutableArray *myMutableArray;
@property (nonatomic, retain) NSTimer *timer;
@end

myApp.m

#import "MyApp.h"

@implementation MyApp
@synthesize myMutableArray;

- (void) viewDidLoad {
    cycleTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(newCycle) userInfo: nil repeats:YES];
MyObject *myCustomUIViewObject = [[MyObject alloc]init];
[myMutableArray addObject:myCustomUIViewObject];
[myCustomUIViewObject release];
NSLog(@"%i",[myMutableArray count]);  /////outputs "1"
}

-(void) newCycle {
    NSLog(@"%i",[myMutableArray count]);  /////outputs "0" ?? why is this??

}
+4  A: 

myApp.m is not retaining the array unless you assign to it using self.myMutableArray, unless you use the self. prefix you do not get the benefit of the (nonatomic, retain).

Your results point to an array that is not allocated at the time you read from it. It's either this or failing to allocate the array before using addObject (unlikely given your NSLog result).

- (void) viewDidLoad {
    self.myMutableArray = [NSMutableArray array];

    ...
}

would probably fix this up.

Adam Eberbach
+2  A: 

Try this

- (void) viewDidLoad {
  cycleTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(newCycle) userInfo: nil repeats:YES];
  MyObject *myCustomUIViewObject = [[MyObject alloc]init];

  NSMutableArray *my_array = [[NSMutableArray alloc] initWithCapacity:3];
  self.myMutableArray = my_array;
  [my_array release];

  [myMutableArray addObject:myCustomUIViewObject];
  [myCustomUIViewObject release];
  NSLog(@"%i",[myMutableArray count]);  /////outputs "1"

}

and don't forget to

- (void) viewDidUnLoad {
  self.myMutableArray = nil;
}

and

- (void) dealloc{
  [myMutableArray release];
  [super dealloc];
}
Allisone