Mona
Mona

Reputation: 6175

Store an array of UIViews in NSUserDefaults

I'm trying to add an array of uiviews to NSDefault but it doesn't seem to be keep the array. Does any one know why? I also tried to store each view in nsvalue before storing it in nsdefault which still didn't work.

NSArray *arr = [[NSArray alloc] initWithObjects:[NSValue valueWithNonretainedObject:myView], nil]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:arr forKey:@"myKey"];

NSArray *resultArray = [defaults objectForKey:@"myKey"];

and resultArray is nil!

Thanks

the reason why I'm trying to do this is because these are the header views of my uitableview. Since it takes time to create them I wanted to create them only once and store them for future access.

Upvotes: 0

Views: 1265

Answers (3)

Robotic Cat
Robotic Cat

Reputation: 5891

A ha! You are not the first person to face this issue. I've not had this type of issue myself but, in the link below, is a blog with code that allows you to cache and re-use your views. Then you would only need to re-create the views when you launch. Example code:

Cache UIViews for re-use in tableview

Upvotes: 1

rmaddy
rmaddy

Reputation: 318854

From the docs for NSUserDefaults:

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.

If you want to put a UIView (why?) in NSUserDefaults, you need to archive it first into an NSData object.

But you need to ask yourself why you want to put a view in NSUserDefaults. You should only be putting bits of data in NSUserDefaults. Views display data. It's easy to redisplay a view once you have the data back. Consider just putting some needed data in NSUserDefaults.

Upvotes: 3

Ezeki
Ezeki

Reputation: 1519

Are you sure you want to do that? It is definitely better to store an array of models to the data base or some file and recreate views from them when needed.

Upvotes: 2

Related Questions