开发者

Array doesn't persist outside viewDidLoad

开发者 https://www.devze.com 2023-01-05 17:36 出处:网络
I\'m facing a strange problem with NSUsrDefaults. Whenever I\'m fetching the data from NSUserDefaults, it\'s getting populated temporarily. I\'m fetching it into viewDidLoad where it\'s fetched.

I'm facing a strange problem with NSUsrDefaults. Whenever I'm fetching the data from NSUserDefaults, it's getting populated temporarily. I'm fetching it into viewDidLoad where it's fetched.

-(void)viewDidLoad{
companies = [NSMutableArray array];
oldCompanies = [[NSUserDefaults standardUserDefaults] arrayForKey:@"companyData"];
if( companies )
{
    for( NSData *data in oldCompanies )
    {
        companyObj = (Company*) [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [companies addObject:companyObj];
    }
}
}

But outside viewDidLoad, whenever I try to access the data, the array "oldCompanies" as well as "companies" are shown "nil".

EDIT: I'm encoding my Company object in a class which subclasses NSCoding like shown below but not allocating or retaining the properties anywhere. Can this be the catch?

- (void)encodeWithCoder:(NSCoder *)encoder
{
//Encode properties, other class variables, etc
[encoder encodeObject:self.companyId forKey:@"id"];
[encoder encodeObject:self.companyTitle forKey:@"title"];
[encoder encodeObject:self.companyImage f开发者_运维问答orKey:@"image"];
}

- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if( self != nil )
{
    //decode properties, other class vars
    self.companyId = [decoder decodeObjectForKey:@"id"];
    self.companyTitle = [decoder decodeObjectForKey:@"title"];
    self.companyImage = [decoder decodeObjectForKey:@"image"];
}
return self;
 }

Can anybody please help?

Thanx in advance.


+array creates an autoreleased array - if you want to take ownership of it per the memory management rules then you need to retain it:

[companies retain];

Or create it so that it isn't autoreleased:

companies = [[NSMutableArray alloc] init];

Or, better, let declared properties do that for you:

// interface, property declaration:
@property(retain, readwrite) NSMutableArray *companies;

// implementation:
@synthesize companies;

// ... using it:
self.companies = [NSMutableArray array];


You are not retaining the array, when you dont do an alloc, or a retain when instatiating an object you get an autoreleased object, in your example companies is autoreleased and is why you cant access it anymore at a later point you should either alloc it [[NSMutableArray alloc] init] or retain it [NSMutableArray array] retain]...either way refer to memory managment guide to learn about objective-c memory managment memory managment ref


Are you trying to access the data before the view is loaded?

Objective-C doesn't reset your pointers for you. If the array isn't "persisted", then the pointer will point to garbage.

0

精彩评论

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