iphone NSMutableArray在方法结束时丢失对象

时间:2010-06-11 01:02:21

标签: iphone objective-c ipad nsmutablearray

在我的应用程序中,一个NSMutableArray在viewDidLoad中填充了一个对象(最终会有很多对象,但我只是做了一个直到我让它正常工作)。我还启动了一个计时器,它启动一个需要每隔几秒访问NSMutableArray的方法。 NSMutableArray在viewDidLoad中工作正常,但只要该方法完成,它就会丢失该对象。

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??

}

2 个答案:

答案 0 :(得分:5)

除非您使用self.myMutableArray前缀,否则myApp.m不会保留数组,除非您使用self.分配给(nonatomic, retain)

您的结果指向您从中读取时未分配的数组。这是或者在使用addObject之前未能分配数组(不太可能给出你的NSLog结果)。

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

    ...
}

可能会解决这个问题。

答案 1 :(得分:2)

试试这个

- (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"

}

并且不要忘记

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

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