How to save data in iOS

后端 未结 6 813
有刺的猬
有刺的猬 2020-12-03 01:40

I\'m making a game and when I close the app (close at multitask manager), all my data is gone! So, My question is very simple: How do I save the data?

相关标签:
6条回答
  • 2020-12-03 01:53

    Swift 3

    Use UserDefaults

    UserDefaults.standard.set(„some value”, „key”)
    let value = UserDefaults.standard.string(„key”)
    

    You can even persist array using this

    0 讨论(0)
  • 2020-12-03 02:01

    Let's say you want to save score and level, which are both properties of an object called dataHolder.

    DataHolder can be created as a singleton, so you don't have to worry too much about from where you access it (its sharedInstance actually):

    It's code would look a bit like this:

    DataHolder.h

    #import <Foundation/Foundation.h>
    
    @interface DataHolder : NSObject 
    
    + (DataHolder *)sharedInstance;
    
    @property (assign) int level;
    @property (assign) int score;
    
    -(void) saveData;
    -(void) loadData;
    
    @end
    

    DataHolder.m

    NSString * const kLevel = @"kLevel";
    NSString * const kScore = @"kScore";
    
    @implementation DataHolder
    
    - (id) init
    {
        self = [super init];
        if (self)
        {
            _level = 0;
            _score = 0;
        }
        return self;
    }
    
    + (DataHolder *)sharedInstance
    {
        static MDataHolder *_sharedInstance = nil;
        static dispatch_once_t onceSecurePredicate;
        dispatch_once(&onceSecurePredicate,^
                      {
                          _sharedInstance = [[self alloc] init];
                      });
    
        return _sharedInstance;
    }
    
    //in this example you are saving data to NSUserDefault's
    //you could save it also to a file or to some more complex
    //data structure: depends on what you need, really
    
    -(void)saveData
    {
        [[NSUserDefaults standardUserDefaults] 
            setObject:[NSNumber numberWithInt:self.score] forKey:kScore];
    
        [[NSUserDefaults standardUserDefaults] 
            setObject:[NSNumber numberWithInt:self.level] forKey:kLevel];
    
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    -(void)loadData
    {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:kScore])
        {
            self.score = [(NSNumber *)[[NSUserDefaults standardUserDefaults] 
                objectForKey:kScore] intValue];
    
            self.level = [(NSNumber *)[[NSUserDefaults standardUserDefaults] 
                objectForKey:kLevel] intValue];
        }
        else
        {
            self.level = 0;
            self.score = 0;
        } 
    }
    
    @end
    

    Don't forget to #import "DataHolder.h" where you need it, or simply put it in ...-Prefix.pch.

    You could perform actual loading and saving in appDelegate methods:

    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
        [[DataHolder sharedInstance] saveData];
    }
    
    - (void)applicationWillEnterForeground:(UIApplication *)application
    {
        [[DataHolder sharedInstance] loadData];
    }
    

    You can access your score and level data from anywhere with [DataHolder sharedInstance].score and [DataHolder sharedInstance].level.

    This might seem like an overkill for a simple task but it sure helps to keep things tidy and it can help you to avoid keeping all the data in appDelegate (which is usually the quick & dirty path to solution).

    0 讨论(0)
  • 2020-12-03 02:05

    [NSUserDefaults standardUserDefaults] is good for small amounts of data like user settings and preferences. Typically you use this to enable users to save various bits of data that define global values such as character preferences, weapons preferences, whatever, etc.

    For larger amounts of data like game level details or achievements or weapons inventory, etc. You will want to use something like Core Data. This is a more formal database that can be easily migrated as your data schema changes. See the docs here: Core Data and Core Data Programming Guide

    0 讨论(0)
  • 2020-12-03 02:08

    There are few ways to save data in ios.

    1. UserDefaults - great way to save a small amount of data.
    2. Keychain - safe location to safe high sensible data like login data and passwords.
    3. Sqlite Database - If your application have a huge amount of structured data
    4. CoreData - based on an object graph that describes the objects that should be saved
    5. Saving Files - Of course you can also directly save all types of files to the file system. However, you can just access the file system within the app container due to security reasons.
    6. Using Realm database - best alternative to Core Data and SQLite db
    7. NSKeyedArchiver and NSKeyedUnarchiver - better way for small amount of objects. // i think so

    ref - http://www.thomashanning.com/data-persistence-ios/

    0 讨论(0)
  • 2020-12-03 02:10

    You can save data in CoreData, SqlLite or NSUserDefaults Update Realm is also an option and very easy to implement.

    0 讨论(0)
  • 2020-12-03 02:12

    I recommend using Realm for more generalized solutions.

    0 讨论(0)
提交回复
热议问题