开发者

iphone NSMutableArray loses objects at end of method

开发者 https://www.devze.com 2023-01-03 14:51 出处:网络
in my app, an NSMutableArray is populated with an object in viewDidLoad (eventually there will be many objects bu开发者_高级运维t I\'m just doing one til I get it working right). I also start a timer

in my app, an NSMutableArray is populated with an object in viewDidLoad (eventually there will be many objects bu开发者_高级运维t 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 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.


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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号