Skip to Content
Swift游戏开发经典实例
book

Swift游戏开发经典实例

by Jonathon Manning, Paris Buttfield-Addison
January 2020
Intermediate to advanced
356 pages
6h 4m
Chinese
China Electric Power Press Ltd.
Content preview from Swift游戏开发经典实例
168
5
5.11
CloudKit
数据库中添加记录
问题
你想将数据保存到
CloudKit
数据库。
解决方案
创建一个
CKRecord
类型的实例,通过它
setObject(_, forKey:)
法来填充数据,
然后用数据库对象
save
方法保存数据。
在创建
CKRecord
实例时,需要指定它的类型。记录的类型是一个简单字符串,这
个字符串相同,则表明这种记录的类型是相同的。
创建好一个
CKRecord
对象之后,你可以向它的字段插入信息,它的字段是通过字
符串形式的
key
来进行索引的。
相比较于这种硬编码字符串的方式,更好的方式是使用
Swift
语言特性,如枚举,
这样编译器就可能发现你在输入中的错误。
举个简单例子,假设你想保存一段纯文本到
CloudKit
。那么我们可以创建一种记录
类型叫作
Note
,相对应的
key
则叫作
content
enum NoteRecordKey : String {
case contents
}
let NoteRecordType = "Note"
这样,你就可以创建你的
CKRecord
对象,向它填充数据,然后保存到数据库。
当你调用
save
方法时,你可以在操作完成时提供一个闭包。这个闭包接收两个参
数:一个是所保存的
CKRecord
,另一个是一个
Error
。这两个参数都是可选的,它
们只会有一个是有值的(另一个则是空)。如果闭包接收到的参数中
CKRecord
有值,
说明保存成功;如果
Error
有值,则说明保存不成功:
func saveNewMessage(text: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

精通機器學習

精通機器學習

Aurélien Géron
FreeBSD® Unleashed

FreeBSD® Unleashed

Brian Tiemann, Michael C. Urban
深入淺出代數

深入淺出代數

Tracey Pilone, Dan Pilone
Swift学习手册

Swift学习手册

Jon Manning, Paris Buttfield-Addison, Tim Nugent

Publisher Resources

ISBN: 9787519840129