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

标签 iphone objective-c ipad nsmutablearray

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

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 不会保留数组,除非您使用 self.myMutableArray 分配给它,除非您使用 self. 前缀,否则您不会获得以下好处(非原子,保留)

您的结果指向一个在您读取时尚未分配的数组。要么是这样,要么是在使用 addObject 之前未能分配数组(不太可能给出您的 NSLog 结果)。

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

    ...
}

可能会解决这个问题。

关于iphone NSMutableArray 在方法结束时丢失对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3019550/

相关文章:

ios - 在同一数据库上使用两个 FMDB 队列(读/写)

iphone - 在计算角度时避免使用 atan2 - atan2 精度

iphone - coreplot 2 图表中的图

ios - '接收器 (<ViewController>) 没有标识符为 'addSegue' 的 segue

iphone - iPhone 开发中的 EXC_BAD_ACCESS

ios - UIImagePickerController 在 ios 9.3 iPad 4 上不能正常工作

iphone - 如何手动读取JSON

ios - 为什么弹出嵌套在 UISplitViewController 中的 UINavigationController 的 Controller 会为整个 splitView 设置动画?

ios - 如何检查 array 在 ios sdk 中是否为 null 或为空?

ios - 解释从 iOS 中的蓝牙体重秤设备接收到的字节