无法在“viewDidLoad”中访问在“init”中初始化的对象

时间:2013-03-08 22:53:20

标签: ios objective-c cocoa-touch initialization

我有一个奇怪的问题:我在“init”方法中加载对象数据。当我尝试在“viewDidLoad”中访问它时,我的应用程序崩溃了。这是代码:

@interface UploadCenterViewController () {
    NSMutableArray *videos;
}

@end

@implementation UploadCenterViewController 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
    if (self) {
        if (![self loadVideos]) {
            [self saveVideos];
        }
    }

    return self;
}

-(void)saveVideos {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *encodedData = [NSKeyedArchiver archivedDataWithRootObject:videos];
    [defaults setObject:encodedData forKey:@"VIDEOS"];
    [defaults synchronize];
}

-(bool)loadVideos {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *encodedData = [defaults objectForKey:@"VIDEOS"];
    if (encodedData) {
        videos = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData:encodedData];

        NSLog(@"array size: %d", [videos count]);

        return true;
    } else {
        videos = [[NSMutableArray alloc] init];
        return false;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%d", [videos count]);
}

加载数据时,“videos”数组包含一个对象。在“viewDidLoad”中访问它时,整个应用程序崩溃。

有没有人有想法?

2 个答案:

答案 0 :(得分:3)

您可能希望保留[NSKeyedUnarchiver unarchiveObjectWithData:encodedData]

的结果

阅读memory management rules

答案 1 :(得分:3)

videos声明为@property,并在任何地方将其用作self.videos。崩溃的原因是,videos在为其分配值后即被释放。 videos的范围仅在该方法内部,因此可能会崩溃。由于您希望在该方法之外使用此方法,因此您需要保留它,并且可以使用@property进行此操作,如下所述。

例如: -

@interface UploadCenterViewController () {}

@property(nonatomic, strong) NSMutableArray *videos;

@end

-(void)saveVideos {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *encodedData = [NSKeyedArchiver archivedDataWithRootObject:self.videos];
    [defaults setObject:encodedData forKey:@"VIDEOS"];
    [defaults synchronize];
}

-(bool)loadVideos {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *encodedData = [defaults objectForKey:@"VIDEOS"];
    if (encodedData) {
        self.videos = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData:encodedData];
        NSLog(@"array size: %d", [self.videos count]);
        return true;
    } else {
        self.videos = [[NSMutableArray alloc] init];
        return false;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%d", [self.videos count]);
}