ios 如何在iOS中保存数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19197448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:05:57  来源:igfitidea点击:

How to save data in iOS

iospersistence

提问by CenoX

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?

我正在制作游戏,当我关闭应用程序(在多任务管理器中关闭)时,我的所有数据都消失了!所以,我的问题很简单:如何保存数据?

回答by Rok Jarc

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

假设您要保存分数和级别,它们都是名为 dataHolder 的对象的属性。

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

DataHolder 可以创建为单例,因此您不必太担心从哪里访问它(sharedInstance实际上是):

It's code would look a bit like this:

它的代码看起来有点像这样:

DataHolder.h

数据持有人.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

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.

不要忘记在需要的地方 #import "DataHolder.h",或者干脆把它放在...-Prefix.pch.

You could perform actual loading and saving in appDelegatemethods:

您可以在appDelegate方法中执行实际加载和保存:

- (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].scoreand [DataHolder sharedInstance].level.

您可以从任何地方使用[DataHolder sharedInstance].score和访问您的分数和级别数据[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).

对于一个简单的任务来说,这似乎是一种矫枉过正,但它确实有助于保持整洁,并且可以帮助您避免将所有数据保留在appDelegate其中(这通常是快速而肮脏的解决方案)。

回答by Cliff Ribaudo

[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.

[NSUserDefaults standardUserDefaults]适用于少量数据,如用户设置和偏好。通常,您可以使用它来使用户能够保存定义全局值的各种数据位,例如角色偏好、武器偏好等。

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 Dataand Core Data Programming Guide

对于大量数据,例如游戏级别详细信息或成就或武器库存等,您将需要使用核心数据之类的数据。这是一个更正式的数据库,可以在您的数据模式更改时轻松迁移。请参阅此处的文档: 核心数据核心数据编程指南

回答by Adnan Aftab

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

您可以将数据保存在 CoreData、SqlLite 或 NSUserDefaults UpdateRealm 中也是一种选择并且非常容易实现。

回答by BatyrCan

There are few ways to save data in ios.

在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
  1. UserDefaults - 保存少量数据的好方法。
  2. 钥匙串 - 安全的高敏感数据(如登录数据和密码)的安全位置。
  3. Sqlite 数据库 - 如果您的应用程序有大量结构化数据
  4. CoreData - 基于描述应该保存的对象的对象图
  5. 保存文件 - 当然您也可以直接将所有类型的文件保存到文件系统中。但是,出于安全原因,您只能访问应用程序容器内的文件系统。
  6. 使用 Realm 数据库 - Core Data 和 SQLite db 的最佳替代方案
  7. NSKeyedArchiver 和 NSKeyedUnarchiver - 少量对象的更好方法。// 我想是这样

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

参考 - http://www.thomashanning.com/data-persistence-ios/

回答by Jakub Pomyka?a

Swift 3

斯威夫特 3

Use UserDefaults

使用用户默认值

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

You can even persist array using this

你甚至可以使用这个持久化数组

回答by Amr Lotfy

I recommend using Realmfor more generalized solutions.

我建议使用Realm来获得更通用的解决方案。