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??
}
myApp.m is not retaining the array unless you assign to it using
self.myMutableArray, unless you use theself.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).would probably fix this up.