简体   繁体   中英

Saving temporary data in userdefaults?

I've got views on my screen that are placed on the screen based on firebase data. When the view is originally planted on the screen it pulls from the saved x and y from firebase and uses that to place itself on the screen.

The views are draggable and so I'm wanting when the user drags the views, leaves the page and comes back for the views to no longer pull from the old firebase data but some locally saved new x /y. Before what I was doing was just updating the x /y on firebase on touches end, but that's super impractical for lots of users doing that at once plus it just seems unnecessary.

The super sloppy idea I had was saving the x / y in the userdefaults when the touches end on one of these views by doing something like:

1) Each view has a firebase UID tied to it, so grab that

2) grab the X and Y positions of the button on touches end

3) Have the key name be the String(UID + "xCoord") and one for Y as well and save the values under there

4) When I'm looking for the x / y values for the view to be drawn in check to see if there's a userdefault set for that UID's Xcoord + Ycoord, otherwise go to firebase for it.

Then to clean up my userdefaults I could check to see if there's any UID the exists for views I'll ever load up again, and if not I can clear out those coordinates (not sure if that's even necessary).

Is this an abysmal way of doing this? Is there a better way to do it? I'd rather not get into core data because I've avoided it like the plague and this seems simple enough to not need it.

Any ideas on how to make this better?

You've basically described pretty much how macOS saves the locations of windows. The feature there called "autosave." User defaults is a fine place to put this.

I'd map just one property for the window, rather than two. You can easily store a CGPoint in user defaults with an NSValue(cgPoint:) . I'd probably prefix something on the property name (like "windowPosition:") rather than just using the UID, but it probably doesn't matter that much. You could also store all window locations in a single property that stores a dictionary. Really, whatever is reasonably convenient. This is more-or-less what user defaults are for, especially in iOS where the user can't directly interact with them. Storing small pieces of data between launches of the program is its whole point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM