Sheehan Alam
Sheehan Alam

Reputation: 60869

How to save array to NSUserDefaults?

I would like to save an array of view controllers in NSUserDefaults, but I am not sure how:

[[NSUserDefaults standardUserDefaults] setObject:tabBarController.viewControllers forKey:@"tabOrder"];

When I read the above line, my tabBarController.viewControllers is blank.

Upvotes: 0

Views: 2049

Answers (2)

Manish Saini
Manish Saini

Reputation: 67

ere you can Save Object With NSUserDefault..

[[NSUserDefaults standardUserDefaults]setObject:[NSKeyedArchiver archivedDataWithRootObject:self.flipsideView.zoznamFunkcii] forKey:@"NSMutableArray"]; [[NSUserDefaults standardUserDefaults]synchronize];

and you make coder and decoder method

  • (id)initWithCoder:(NSCoder *)decoder { if (self = [super init]) { self.toolResult = [decoder decodeObjectForKey:@"obj1"]; self.toolNotes = [decoder decodeObjectForKey:@"obj2"];

    } return self; }

  • (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:self.toolResult forKey:@"obj1"]; [encoder encodeObject:self.toolNotes forKey:@"obj2"];

}

your Data Save Into NsuserDefault When you Get Data From NsUserDefault then you Use like [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"NSMutableArray"]];

Upvotes: 0

MrMage
MrMage

Reputation: 7487

The view controllers in this array are not serializable, and thus won't be saved to NSUserDefaults.

From the NSUserDefaults reference:

The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects. See “What is a Property List?” in Property List Programming Guide.

You should re-initialize your view controllers on the next load. You can however serialize their data to NSUserDefaults to some custom fields.

Upvotes: 2

Related Questions