1

我有一个奇怪的问题:我在“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”中访问它时,整个应用程序崩溃。

有人有想法吗?

4

2 回答 2

3

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

阅读内存管理规则

于 2013-03-08T22:56:42.297 回答
3

声明videos为 an@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]);
}
于 2013-03-08T22:58:16.730 回答