How to save a subView that has been added using NSUserDefaults?

I work in a book application and I want to use a page marker to help the user remember where he stopped reading. So I added a button with an image ("mark.png"). When viewing as a chapter, a tag view will be added, and if it is deleted again, the tag will be removed from superView . I am using this code:

 - (void)showMark { if (![markView superView]) { [chapterOne addSubView:markView]; } else { [markView removeFromSuperView]; } } 

It works fine, but sometime I exit the application and run the tag view again, and how can I save it? I found several forums about NSUserDefaults for saving actions, but I really don't know how to use it with my code. Any help would be appreciated.

+4
source share
3 answers

You cannot use NSUserDefaults to save entire views, but you can save options that help determine where the bookmark should be set.

For example, if you use an alphabetic character by page number, you can save the page in NSUserDefaults when the user leaves the view controller.

Example:

 [[NSUserDefaults standardUserDefaults] setInteger:23 forKey:@"bookMarkPage"]; [[NSUserDefaults standardUserDefaults] synchronize]; 

When the user returns to the view controller, you can check if there is a bookmark:

 if ([[NSUserDefaults standardUserDefaults] objectForKey:@"bookMarkPage"] != nil) { int pageNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"bookMarkPage"]; [self setBookmarkForPage:pageNumber]; } 

Possible way to build bookmarks:

 - (void) setBookmarkForPage:(Int)pageNumber { // run through the logic of placing the bookmark on the correct page } 

You can use any parameters necessary to determine the placement of the book's character. When a user initially places a bookmark, what parameters do you use to figure out where to place the bookmark? Try using the same logic when the user first places a bookmark.

+3
source

I do not know exactly what you want to save, but you can use any data using NSUserDefaults , for example:

 [[NSUserDefaults standardUserDefaults] setInteger:123 forKey:@"CurrentPageNumber"]; 

When you have set all the necessary values, save them:

 [[NSUserDefaults standardUserDefaults] synchronize]; 

Then, when the application opens, check if the value is set. If you draw a marker.

 if ([defaults valueForKey:@"CurrentPageNumber"] != nil) { int pageNumber = [defaults valueForKey:@"CurrentPageNumber"] if (pageNumber == 1) { [chapterOne addSubView:markView]; } else { [markView removeFromSuperView]; } } 
+2
source

Other answers provide excellent solutions to this problem. To clarify, UIView or any derivatives are not supported for NSUserDefaults . NSUserDefaults allows you to use only primitive object types ( NSString, NSNumber, NSArray, and NSDictionary ). Maybe one or two I missed. But UIView or UIViewController object types cannot be stored in NSUserDefaults .

0
source

All Articles