ios开发应用领域_ios领域介绍

ios开发应用领域

The Realm mobile database is a data-storage solution for mobile and web development. At the time of writing this article, Realm offers a solution for Java, Kotlin, Swift, Obj-C, JavaScript, and .NET. As the article title indicates, we’ll be focusing on iOS — and specifically, Swift. This article assumes you have a basic understanding of Swift and iOS development.

Realm移动数据库是用于移动和Web开发的数据存储解决方案。 在撰写本文时,Realm提供了针对Java,Kotlin,Swift,Obj-C,JavaScript和.NET的解决方案。 如文章标题所示,我们将重点关注iOS,尤其是Swift。 本文假定您对Swift和iOS开发有基本的了解。

At the time of writing this article, you can use the Swift Package Manager (SPM), CocoaPods, or Carthage to add Realm to your project. I’ll be using SPM in this guide, as it’s the quickest and easiest way to get started. If you haven’t used SPM before, you can learn how to use it from the following YouTube video.

在撰写本文时,您可以使用Swift Package Manager(SPM),CocoaPods或Carthage将Realm添加到您的项目中。 在本指南中,我将使用SPM,因为它是上手最快,最简单的方法。 如果您以前从未使用过SPM,则可以从以下YouTube 视频中学习如何使用它。

To follow along with this guide, I’d suggest downloading the completed project here and having this article open side by side with the project.

为了遵循本指南,建议您在此处下载完成的项目并与项目并行打开本文。

If you are on a mobile device or on a Windows PC, just know that all actions performed will be in viewDidLoad in the initial view controller. You’ll notice several of the write transactions are in their own private methods. This is an attempt to keep viewDidLoad relatively clean and to performs checks to make sure our test data isn’t duplicated every time we run the app.

如果您在移动设备或Windows PC上,只需知道执行的所有操作都将在初始视图控制器的viewDidLoad中。 您会注意到一些写事务在它们自己的私有方法中。 这是为了保持viewDidLoad相对干净并执行检查以确保每次运行该应用程序时都不会重复测试数据。

Once you’ve downloaded the project and have it open, hit Cmd+B to build the project. This may take a few mins to complete.

下载完项目并将其打开后,请按Cmd+B生成项目。 这可能需要几分钟的时间才能完成。

In this guide, our data model will represent a bank, its manager, and its customers. This way, I can illustrate one-to-one and one-to-many relationships.

在本指南中,我们的数据模型将代表银行,经理和客户。 这样,我可以说明一对一和一对多的关系。

什么是境界? (What’s Realm?)

Realm is an object database that supports relationships between objects. If you’re coming from the SQL world, Realm will feel very familiar to you. Later on in this guide, we’ll launch Realm Studio, and you’ll be able to see the tables that represent each class and the rows that represent each object.

领域是支持对象之间关系的对象数据库。 如果您来自SQL世界,Realm对您会非常熟悉。 在本指南的后面部分,我们将启动Realm Studio,您将能够看到代表每个类的表和代表每个对象的行。

When you want to update an object’s value, you can make the change directly on the object itself in a write transaction. The Realm mobile database is considered a replacement for SQLite and Core Data.

当您要更新对象的值时,可以在write事务中直接在对象本身上进行更改。 Realm移动数据库被认为是SQLite和Core Data的替代品。

In simple terms, a realm is where your data is stored and managed. You can use more than one realm in a single project, but lets keep it basic for this article. Let’s get started.

简而言之, 领域就是存储和管理数据的地方。 您可以在一个项目中使用多个领域,但对于本文而言,请使其保持基本状态。 让我们开始吧。

下载Realm Studio (Download Realm Studio)

First, I recommend downloading Realm Studio and installing it. This will allow you to view the data saved to the local realm.

首先,我建议下载Realm Studio并安装它。 这将使您可以查看保存到本地领域的数据。

默认领域入门 (Getting Started With the Default Realm)

Creating a default local realm is incredibly easy. With your project open, navigate to the ViewController.swift file, import RealmSwift, and place the following in the ViewController class (preferably at the top):

创建默认本地领域非常简单。 在您的项目打开的情况下,导航到ViewController.swift文件,导入RealmSwift 然后将以下内容放入ViewController类(最好在顶部):

Now run your project in a simulator (Cmd + R). Once the app starts up, the default realm is created. All you need is this one line of code to get started.

现在,在模拟器( Cmd + R )中运行您的项目。 应用启动后,将创建默认领域。 您所需要做的就是开始编写这一行代码。

Note: During this guide or during your own development, you may need to delete the app from the simulator to remove the prior realm and force the creation of a new one. This typically happens when you remove a persisted property that the realm model is expecting. You can find more information here in the Realm docs.

注意:在本指南或您自己的开发过程中,您可能需要从模拟器中删除该应用程序以删除先前的领域并强制创建一个新的领域。 当您删除领域模型期望的持久属性时,通常会发生这种情况。 你可以找到更多的信息, 这里的境界文档。

自定义领域配置 (Custom Realm configuration)

While you can get started with the one line of code above, there are several options you can set on the Realm.Configuration struct. Since this guide is an intro to Realm, we won’t go into the specifics, but the several different options are shown in the screenshot below.

虽然您可以从上面的一行代码开始,但是可以在Realm.Configuration结构上设置几个选项。 由于本指南是Realm的简介,因此我们不再赘述,但是下面的屏幕快照中显示了几个不同的选项。

Image for post

查看模型和数据库内容 (Viewing the Model and Database Contents)

Add the following to the end of the viewDidLoad method:

将以下内容添加到viewDidLoad方法的末尾:

This will print the location to the debug area. Copy the location link (excluding file://) and open Realm Studio. Click on Open Realm File, hit Cmd+Shift+G, and paste the link in the dialog box. Click on the default.realm file, and click Open. There won’t be any data in the realm yet, but we’ll get to that soon.

这会将位置打印到调试区域。 复制位置链接(不包括file:// ) 并打开Realm Studio。 单击“打开领域文件”,单击“ Cmd+Shift+G ,然后将链接粘贴到对话框中。 单击default.realm文件,然后单击“打开”。 领域中还没有任何数据,但是我们很快就会解决。

人际关系 (Relationships)

一对一 (One-to-one)

To create a one-to-one relationship, set the property to the Realm class you want to relate. In our example, each bank can have one branch manager. Be sure this type is optional. The property below will be part of the Bank class.

要创建一对一关系,请将属性设置为要关联的Realm类。 在我们的示例中,每个银行可以有一个分支机构经理。 确保此类型是可选的。 下面的属性将属于Bank类。

@objc dynamic var branchManager: BranchManager?

一对多 (One-to-many)

To create a one-to-many relationship, set the property to the Realm-specific List type of the many class. In our example, each bank can have many customers. The following will be a part of the Bank class.

要创建一对多关系,请将属性设置为many类的特定于领域的List类型。 在我们的示例中,每个银行可以有许多客户。 以下内容将成为Bank类的一部分。

let customers = List<Customer>()

多对多 (Many-to-many)

We won’t be covering this in our example, but know that it’s available. Here’s something from the Realm docs:

在我们的示例中,我们不会进行介绍,但是知道它是可用的。 这是Realm文档的内容:

“You can can create a relationship to any number of objects or supported primitive values using List properties”

“您可以使用List属性创建与任意数量的对象或受支持的原始值的关系”

Find more about Realm’s many-to-many relationship in their documentation.

在他们的文档中找到有关Realm 多对多关系的更多信息

(Inverse)

To create an inverse relationship, use the Realm-specific LinkObjects struct. In our example, we’ll want to be able to find what bank each customer is a member of. The following will be part of the Customer class. Be sure the init property string matches the many property in the Bank class.

要创建关系,请使用特定于领域的LinkObjects结构。 在我们的示例中,我们将希望能够找到每个客户所属的银行。 以下内容将成为Customer类的一部分。 确保init属性字符串与Bank类中的many属性匹配。

let bank = LinkingObjects(fromType: Bank.self, property: "customers")

创建数据模型 (Creating the Data Model)

Classes are used to create the model objects and the must subclass object. Structs and enums aren’t supported for model types. Creating properties of a class must be a var and prefixed with @objc dynamic. Properties must be given an initial value or be optional.

类用于创建模型对象和must子类对象。 模型类型不支持结构和枚举。 创建类的属性必须是var并以@objc dynamic为前缀。 必须给属性一个初始值或可选的。

支持的类型 (Supported types)

Bool, Int, Int8, Int16, Int32, Int64, Double, Float, String, Date, and Data are supported. All of these properties can be optional. Realm’s docs provide an excellent cheat sheet:

BoolIntInt8Int16Int32Int64DoubleFloatStringDateData 。 所有这些属性可以是可选的。 Realm的文档提供了出色的备忘单:

Image for post
Realm docs 领域文档

创建我们的模型 (Creating our model)

In this guide, we’re going to create a model to represent a bank. Our model will consist of three classes: Bank, branchManager, and Customer. These model classes will be added to the Model.swift file.

在本指南中,我们将创建一个代表银行的模型。 我们的模型将包括三个类: BankbranchManagerCustomer. 这些模型类将添加到Model.swift文件中。

Bank

银行

Here’s a breakdown:

这是一个细分:

  • Each bank will have a unique ID generated by UUID().uuidString

    每个银行将有一个由UUID().uuidString生成的唯一ID UUID().uuidString

  • Each Bank will have one branchManager

    每家Bank都有一个branchManager

  • Each Bank will have many customers

    每个Bank将有很多客户

  • A bank can either be a credit union, central bank, or retail bank. As commented in the code, Realm will ignore the nested enum.

    银行可以是信用合作社,中央银行或零售银行。 如代码中所述,Realm将忽略嵌套的枚举。
  • The CLLocation computed property will be ignored by Realm

    CLLocation计算的属性将被Realm忽略

Branch manager

分公司经理

Here’s a breakdown:

这是一个细分:

  • Each BranchManager will have a unique ID. Think of this as an employee ID.

    每个BranchManager将具有唯一的ID。 将此视为员工ID。

  • Nothing else is too special about this class

    这堂课没什么特别的

Customer

顾客

Here’s a breakdown:

这是一个细分:

  • Each Customer will have a unique account number

    每个Customer都有一个唯一的帐号

  • Properties keep track of their starting and current balances

    物业跟踪其开始和当前余额
  • A property to hold the date they became a member of the bank

    持有其成为银行会员之日的财产
  • A computed property that assists with providing their full name

    计算出的属性,可帮助提供其全名
  • An inverse relationship to Bank. I’ll show you later how to retrieve the customer’s bank from this inverse property.

    Bank的逆关系。 稍后我将向您展示如何从该逆属性中检索客户的银行。

主键 (Primary keys)

If you’re familiar with the relationship databases, you’re probably wondering if Realm supports auto-incrementing IDs or a way to retrieve a specific item. They don’t support auto-incrementing IDs; however, they do support primary keys. Keep in mind, once a primary key is set, it can’t be changed.

如果您熟悉关系数据库,您可能想知道Realm是否支持自动递增ID或检索特定项目的方法。 它们不支持自动递增ID。 但是,它们确实支持主键。 请记住,一旦设置了主键,就无法更改。

创建模型对象 (Creating a Model Object)

Lets finally create an object to persist to the database. At this point in the guide, you should have the default realm created and three model classes.

最后,让我们创建一个对象以保留到数据库。 在本指南的这一点上,您应该已经创建了默认领域和三个模型类。

Anytime you want to create a new object or change an existing object, you must be in a Realm write transaction. A write transaction looks like this:

每当您要创建新对象或更改现有对象时,都必须处于Realm write事务中。 write事务如下所示:

Of course, in a production app, you should wrap this in a do catch block to catch any potential errors.

当然,在生产应用中,您应该将其包装在do catch块中以捕获任何潜在的错误。

创建两个客户和一个分支经理 (Create two customers and a branch manager)

Lets create a couple customers and a branch manager. We can add this write transaction to the viewDidLoad method:

让我们创建一对客户和一个分支经理。 我们可以将此write事务添加到viewDidLoad方法中:

Build and run the project. You have should have three total objects persisted to your Realm database. We’ll use these objects to relate to and from the Bank class. Now, every time you run the project, these objects will be available for use.

生成并运行项目。 您应该将三个对象共存到您的Realm数据库中。 我们将使用这些对象与Bank类进行关联。 现在,每次您运行项目时,这些对象将可供使用。

建立银行 (Create a bank)

Now let’s create the Bank object. We can add this write transaction to the viewDidLoad method:

现在让我们创建Bank对象。 我们可以将此write事务添加到viewDidLoad方法中:

We’ll cover how to add the customer and branch manager relationships later in the guide because it’ll require you to know how to query items from the database.

在本指南的后面部分,我们将介绍如何添加客户和分支经理关系,因为它将需要您知道如何从数据库中查询项目。

取回物品 (Retrieving Items)

The primary way to retrieve objects from the realm is to use the Results class. This class conforms to the RealmCollection protocol, so you iterate over each item, retrieve an item by index, etc. We’ll add the following to viewDidLoad:

从领域检索对象的主要方法是使用Results类。 此类符合RealmCollection协议,因此您可以遍历每个项目,按索引检索一个项目等。我们将以下内容添加到viewDidLoad

Since we only have one branch manager and one bank in our data set, we can safely call .first! to retrieve the branch manager and the bank.

由于我们的数据集中只有一个分支机构经理和一个银行,因此我们可以安全地致电.first! 检索分支机构经理和银行。

修改物件 (Modifying Objects)

Modifying an object’s property is extremely simple. Retrieve an object from the realm, and modify the property directly in a write transaction.

修改对象的属性非常简单。 从领域中检索对象,然后直接在write事务中修改属性。

In our example, let’s say the branch manager got married and changed her last name from Scott to Miller. Using the branchManager object we retrieved above, let’s change her last name. We’ll add the following to viewDidLoad just below where we retrieved the bank, customers, and branch manager:

在我们的示例中,假设分支机构经理结婚,并将姓氏从Scott更改为Miller 。 使用我们在上面检索的branchManager对象,让我们更改她的姓氏。 我们将在以下位置将以下内容添加到viewDidLoad中,该位置位于检索银行,客户和分支机构经理的位置:

That’s it! That’s all it takes to change the value of an object.

而已! 这就是更改对象的值所需的全部。

添加关系 (Adding Relationships)

All three constants are of the type Result, which, as mentioned above, together are a Realm collection.

这三个常量的类型均为Result ,如上所述,它们一起是Realm集合。

Let’s create the relationship between the bank and the branch manager, then between the bank and its customers. At the end of viewDidLoad, we’ll add the following:

让我们在银行与分支机构经理之间,然后在银行与客户之间建立关系。 在viewDidLoad的末尾,我们将添加以下内容:

Note the actions above are in a Realm write transaction. We set the one-to-one relationship between the bank and the branch manager. Then, we set the one-to-many relationship between the bank and its customers by appending each customer to the bank’s customer List type. If you open the realm in Realm Studio, you’ll be able to see the relationships have been established.

请注意,以上操作在Realm write事务中。 我们设置银行和分支机构经理之间的一对一关系。 然后,通过将每个客户附加到银行的客户List类型,设置银行与其客户之间的一对多关系。 如果您在Realm Studio中打开领域,则可以看到已建立关系。

从逆关系中检索客户的银行 (Retrieving the customer’s bank from the inverse relationship)

To retrieve a customer’s bank from the Customer class, you call .first! on the bank property. Add the following to viewDidLoad below the section where you added the relationships:

要从“ Customer类中检索客户的银行,请致电.first!bank财产上。 将以下内容添加到添加关系的部分下面的viewDidLoad中:

Since the bank to customer relationship is one-to-many, we can safely call .first! on the inverse property bank.

由于银行与客户之间的关系是一对多的,因此我们可以放心地致电.first! 在逆财产bank

筛选结果 (Filtering Results)

Realm collections can be filtered by using the .filter higher-order function. You can use the dollar syntax or create an NSPredicate. Developers coming from Core Data should be pleased to hear you can use NSPredicates to filter Realm collections. Add the following to the end of viewDidLoad:

可以使用.filter高阶函数来过滤领域集合。 您可以使用dollar语法或创建NSPredicate 。 来自Core Data的开发人员应该很高兴听到您可以使用NSPredicate过滤Realm集合。 将以下内容添加到viewDidLoad的末尾:

The constant jonCustomer should include all customers with the first name Jon. In our example, there’s only one, so we can use .first? to retrieve the Jon Smith customer object.

常量jonCustomer应该包括所有名字为Jon客户。 在我们的示例中,只有一个,因此我们可以使用.first? 检索Jon Smith客户对象。

谓词 (Predicates)

To perform advanced filtering, several predicates are supported: IN, BETWEEN, AND, OR, NOT, BEGINSWITH, CONTAINS, ENDSWITH, LIKE, ANY, NONE, and@count.

为了执行高级过滤,支持以下几个谓词: INBETWEENAND ORNOTBEGINSWITHCONTAINSENDSWITHLIKEANYNONE@count

在生产应用中使用领域 (Using Realm in a Production App)

I use the Realm mobile database paired with Realm Cloud in my personal finance app, seventytwo. I haven’t noticed any down time with Realm Cloud, and it’s been extremely reliable. The amount of time it takes to sync data between devices is almost instantaneous.

我在个人理财应用程序72中使用了Realm移动数据库和Realm Cloud配对。 我没有注意到Realm Cloud的任何停机时间,并且它非常可靠。 设备之间同步数据所花费的时间几乎是瞬时的。

结论 (Conclusion)

Realm is an excellent choice if you’re looking for a mobile-database solution. Better yet, Realm also has a product called Realm Cloud which allows you to persist data to more than one device and store the user’s data in the cloud. Please note, MongoDB purchased Realm in 2019. If you’re interested in learning more about the direction of Realm, see the roadmap here.

如果您正在寻找移动数据库解决方案,那么Realm是一个绝佳的选择。 更好的是,Realm还具有一个称为Realm Cloud的产品,该产品使您可以将数据持久存储到多个设备上,并将用户的数据存储在云中。 请注意,MongoDB在2019年购买了Realm。如果您有兴趣了解有关Realm方向的更多信息,请参阅此处的路线图。

You can view this entire project here on GitHub.

您可以查看此整个项目在这里 GitHub上。

资源资源 (Resources)

翻译自: https://medium.com/better-programming/an-intro-to-realm-for-ios-2633162952f1

ios开发应用领域

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值