https://rainsoft.io/mastering-swift-essential-details-about-strings/


Mastering Swift: essential details about strings

String type is an important component of any programming language. The most useful information that user reads from the window of an iOS application is pure text.

To reach a higher number of users,the iOS application must be internationalised and support a lot of modern languages. The Unicode standard solves this problem,but creates additional complexity when working with strings.

On one hand,the language should provide a good balance between the Unicode complexity and the performance when processing strings. On the other hand,it should provide developer with comfortable structures to handle strings.

In my opinion,Swift does a great job on both hands.

Fortunately Swift's string is not a simple sequence of UTF-16 code units,like in JavaScript or Java.
In case of a sequence of UTF-16 code units it's a pain to do Unicode-aware string manipulations: you might break a surrogate pair or combining character sequence.

Swift implements a better approach. The string itself is not a collection,instead it provides views over the string content that may be applied according to situation. And one particular view,String.CharacterView,is fully Unicode-aware.

Forlet myStr = "Hello,world"you can access the following string views:

  • myStr.charactersisString.CharacterView. Valuable to access graphemes,that visually are rendered as a single symbol. The most used view.
  • myStr.unicodeScalarsisString.UnicodeScalarView. Valuable to access the Unicode code point numbers as 21-bit integers
  • myStr.utf16isString.UTF16View. Useful to access the code unit values encoded in UTF16
  • myStr.utf8isString.UTF8View. Valuable to access the code unit values encoded in UTF8

Most of the time developer deals with simple string characters,without diving into details like encoding or code units.

CharacterViewworks nice for most of the string related tasks: iteration over the characters,counting the number of characters,verify substring existence,access by index,different manipulations and so on.
Let's see in more details how these tasks are accomplished in Swift.

1.CharacterandCharacterViewstructures

String.CharacterViewstructure is a view over string content that is a collection ofCharacter.

To access the view from a string,usecharactersstring property:

Try in Swift sandbox
let message = "Hello,world"  
let characters = message.characters  
print(type(of: characters)) // => "CharacterView" 

message.charactersreturns theCharacterViewstructure.

The character view is a collection ofCharacterstructures. For example,let's access the first character in a string view:

let firstCharacter .characters.first! (firstCharacter) // => "H" : firstCharacter) // => "Character" let capitalHCharacter: Character "H" (capitalHCharacter == firstCharacter) // => true

message.characters.firstreturns an optional that is the first character"H".
The character instance represents a single symbolH.

In Unicode termsHisLatin Capital letter H,0)">U+0048code point.

Let's go beyond ASCII and see how Swift handles composite symbols. Such characters are rendered as a single visual symbol,but are composed from a sequence of two or moreUnicode scalars. Strictly such characters are namedgrapheme clusters.

Important:CharacterViewis a collection of grapheme clusters of the string.

Let's take a closer look atgrapheme. It may be represented in two ways:

  • UsingU+00E7LATIN SMALL LETTER C WITH CEDILLA: rendered asç
  • Or using a combining character sequence:U+0063LATIN SMALL LETTER Cplus the combining markU+0327COMBINING CEDILLA. The grapheme is composite:c+◌̧=

Let's pick the second option and see how Swift handles it:

"c\u{0327}a va bien" // => "ça va bien" ) // => "ç" let combiningCharacter"c\u{0327}" (combiningCharacter firstCharactercontains a single graphemethat is rendered using two Unicode scalarsU+0063andU+0327.

Characterstructure accepts multiple Unicode scalars as long as they create a single grapheme. If you try to add more graphemes into a singleCharacter,Swift triggers an error:

let singleGrapheme"c\u{0327}\u{0301}" // Works (singleGrapheme) // => "ḉ" let multipleGraphemes"ab" // Error!

Even ifsingleGraphemeis composed of 3 Unicode scalars,it creates a single graphemeḉ.
multipleGraphemestries to create aCharacterfrom 2 Unicode scalars. This creates 2 separated graphemesaandbin a singleCharacterstructure,which is not allowed.

2. Iterating over characters in a string

CharacterViewcollection conforms toSequenceprotocol. This allows to iterate over the view characters in afor-inloop:

let weather "rain" for char in weather.characters { (char) } // => "r" // => "a" // => "i" // => "n"

Each character fromweather.charactersis accessed usingfor-inloop. On every iterationcharvariable is assigned with a character fromweatherstring:"r",0)">"a",0)">"i"and"n".

As an alternative,you can iterate over the characters usingforEach(_:)method,indicating a closure as the first argument:

"rain" weather.forEach { char in } // => "r" // => "a" // => "i" // => "n"

The iteration usingforEach(_:)method is almost the same asfor-in,only that you cannot usecontinueorbreakstatements.

To access the index of the current character in the loop,0)">CharacterViewprovides theenumerated()method. The method returns a sequence of tuples(index,character):

for (index, char) .enumerated() ("index: \(index),char: \(char)"} // => "index: 0,char: r" // => "index: 1,char: a" // => "index: 2,char: i" // => "index: 3,char: n"

enumerated()method on each iteration returns tuplesindexvariable contains the character index at the current loop step. Correspondinglycharvariable contains the character.

3. Counting characters

Simply usecountproperty of theCharacterViewto get the number of characters:

"sunny" (weathercount) // => 5

weather.characters.countcontains the number of characters in the string.

Each character in the view holds a grapheme. When an adjacent character (for example acombining mark) is appended to string,you may find thatcountproperty is not increased.

It happens because an adjacent character does not create a new grapheme in the string,instead it modifies an existingbase Unicode character. Let's see an example:

var drink "cafe" (drink) // => 4 drink +"\u{0301}" ) // => "café" ) // => 4

Initiallydrinkhas 4 characters.
When the combining markU+0301COMBINING ACUTE ACCENTis appended to string,it modifies the previous base charactereand creates a new grapheme. The propertycountis not increased,because the number of graphemes is still the same.

4. Accessing character by index

Swift doesn't know about the characters count in the string view until it actually evaluates the graphemes in it. As result a subscript that allows to access the character by an integer index directly does not exist.
You can access the characters by a special typeString.Index.

If you need to access the first or last characters in the string,the character view structure hasfirstandlastproperties:

let season "summer" (season!) // => "s" last) // => "r" let empty "" (emptyfirst == nil) // => true last ) // => true

Notice thatlastproperties are optional typeCharacter?.
In the empty stringemptythese properties arenil.

To get a character at specific position,you have to useString.Indextype (actually an alias ofString.CharacterView.Index). String offers a subscript that acceptsString.Indexto access the character,as well as pre-defined indexesmyString.startIndexandmyString.endIndex.

Using string index type,let's access the first and last characters:

let color "green" let startIndex = color.startIndex let beforeEndIndex index(before: color.endIndex) (color[startIndex]) // => "g" [beforeEndIndex) // => "n"

color.startIndexis the first character index,socolor[startIndex]evaluates tog.
color.endIndexindicates thepast the endposition,or simply the position one greater than the last valid subscript argument. To access the last character,you must calculate the index right before string's end index:color.index(before: color.endIndex).

To access characters at position by an offset,use theoffsetByargument ofindex(theIndex,offsetBy: theOffset)method:

let secondCharIndex .startIndex: 1) let thirdCharIndex 2[secondCharIndex) // => "r" [thirdCharIndex) // => "e"

Indicating theoffsetByargument,you can access the character at specific offset.

Of courseoffsetByargument is jumping over string graphemes,i.e. the offset applies overCharacterinstances of string'sCharacterView.

If the index is out of range,Swift generates an error:

let oops 100) // Error!

To prevent such situations,indicate an additional argumentlimitedByto limit the offset:limitedBy: theLimit). The function returns an optional,which isnilfor out of bounds index:

) if let charIndex = oops "Correct index"} else { "Incorrect index"} // => "Incorrect index"

oopsis an optionalString.Index?. The optional unwrap verifies whether the index didn't jump out of the string.

5. Checking substring existence

The simplest way to verify the substring existence is to callcontains(_ other: String)string method:

import Foundation let animal "white rabbit" (animalcontains"rabbit""cat") // => false

animal.contains("rabbit")returnstruebecauseanimalcontains"rabbit"substring.
Correspondinglyanimal.contains("cat")evaluates tofalsefor a non-existing substring.

To verify whether the string has specific prefix or suffix,the methodshasPrefix(_:)andhasSuffix(_:)are available. Let's use them in an example:

hasPrefix"white") // => true hasSuffix"white"is a prefix and"rabbit"is a suffix of"white rabbit". So the corresponding method callsanimal.hasPrefix("white")andanimal.hasSuffix("rabbit")returntrue.

When you need to search for a particular character,it makes sense to query directly the character view. For example:

"white rabbit" let aChar"a" let bChar"b" (aCharcontains { $0 == aChar || $== bChar }) // => true

contains(_:)verifies whether the character view has a particular character.
The second function form accepts a closure:contains(where predicate: (Character) -> Bool)and performs the same verification.

6. String manipulation

The string in Swift is avalue type. Whether you pass a string as an argument on function call,assign it to a variable or constant - every time acopyof the original string is created.

A mutating method call changes the string in place.

This chapter covers the common manipulations over strings.

Append to string a character or another string

The simplest way to append to string is+=operator. You can append an entire string to original one:

var bird "pigeon" bird " sparrow" (bird) // => "pigeon sparrow"

String structure provides a mutating methodappend(). The method accepts a string,a character or even a sequence of characters,and appends it to the original string. For instance:

"pigeon" let sChar"s" birdappend(sChar) // => "pigeons" bird" and sparrows") // => "pigeons and sparrows" bird(contentsOf: " fly") // => "pigeons and sparrows fly"

Extract a substring from string

The methodsubstring()allows to extract substrings:

  • from a specific index up to the end of string
  • from the the start up to a specific index
  • or based on a range of indexes.

Let's see how it works:

let plant "red flower" let strIndex = plant(plant4substring(from: strIndex) // => "flower" (to) // => "red " let index "f"{ let flowerRange = index..<plant.endIndex (with: flowerRange) // => "flower" }

The string subscript accepts a range or closed range of string indexes. This helps extracting substrings based on ranges of indexes:

"green tree" let excludeFirstRange = plant.endIndex [excludeFirstRange) // => "reen tree" let lastTwoRange : -[lastTwoRange) // => "ee"

Insert into string

The string type provides the mutating methodinsert(). The method allows to insert a character or a sequence of characters at specific index.

The new character or sequence is inserted before the element currently at the specified index.

See the following sample:

var plant "green tree" plantinsert"s": plant) // => "green trees" plant"nice ") // => "nice green trees"

Remove from string

The mutating methodremove(at:)removes the character at an index:

var weather "sunny day" = weather" "{ weatherremove(at: index) ) // => "sunnyday" }

You can remove characters in the string that are in a range of indexes usingremoveSubrange(_:):

6let range <weather.endIndex weatherremoveSubrange(range) // => "sunny"

Replace in string

The methodreplaceSubrange(_:with:)accepts a range of indexes that should be replaced with a particular string. The method is mutating the string.

Let's see a sample:

<index weatherreplaceSubrange"rainy") // => "rainy day" }

The character view mutation alternative

Many of string manipulations described above may be applied directly on string's character view.

It is a good alternative if you find more comfortable to work directly with a collection of characters.

For example you can remove characters at specific index,or directly the first or last characters:

var fruit "apple" fruit: fruit(fruit) // => "pple" fruitremoveFirst) // => "ple" fruitremoveLast) // => "pl"

To reverse a word usereversed()method of the character view:

"peach" var reversed = Stringreversed(reversed) // => "hcaep"

You can easily filter the string:

let fruit "or*an*ge" let filtered = fruitfilter in return char != "*" } (filtered) // => "orange"

Map the string content by applying a transformer closure:

let mapped map { char -> Character if char == "*" { return "+" } return char (mapped) // => "or+an+ge"

Or reduce the string content to an accumulator value:

let numberOfStars reduce(0{ countStarsin if (char "*"{ return countStarts + 1 } return countStars } (numberOfStars) // => 2

7. Final words

At first sight,the idea of different types of views over string's content may seem overcomplicated.

In my opinion it is a great implementation. Strings can be viewed in different angles: as a collection of graphemes,UTF-8 or UTF-16 code units or simple Unicode scalars.

Just pick the view depending on your task. In most of the cases it isCharacterView.

The character view deals with graphemes that may be compound from one or more Unicode scalars. As result the string cannot be integer indexed (like arrays). Instead a special type of index is applicable:String.Index.

Special index type adds a bit of complexity when accessing individual characters or manipulating strings. I agree to pay this price,because having truly Unicode-aware operations on strings is awesome!

Do you find string views comfortable to use? Write a comment bellow and let's discuss!

P.S.You might be interested to read mydetailed overview of array and dictionary literals in Swift.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


效率成吨提升之代码生成器-蓝湖工具神器iOS,Android,Swift,Flutter
软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘贴.待开发的功能:1.支持自动生成约束2.开发设置页面3.做一个浏览器插件,支持不需要下载整个工程,可即时操作当前蓝湖浏览页面4.支持Flutter语言模板生成5.支持更多平台,如Sketch等6.支持用户自定义语言模板
【Audio音频开发】音频基础知识及PCM技术详解
现实生活中,我们听到的声音都是时间连续的,我们称为这种信号叫模拟信号。模拟信号需要进行数字化以后才能在计算机中使用。目前我们在计算机上进行音频播放都需要依赖于音频文件。那么音频文件如何生成的呢?音频文件的生成过程是将声音信息采样、量化和编码产生的数字信号的过程,我们人耳所能听到的声音频率范围为(20Hz~20KHz),因此音频文件格式的最大带宽是20KHZ。根据奈奎斯特的理论,音频文件的采样率一般在40~50KHZ之间。奈奎斯特采样定律,又称香农采样定律。...............
见过仙女蹦迪吗?一起用python做个小仙女代码蹦迪视频
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿遍又亿遍,久久不能离开!看着小仙紫姐姐的蹦迪视频,除了一键三连还能做什么?突发奇想,能不能把舞蹈视频转成代码舞呢?说干就干,今天就手把手教大家如何把跳舞视频转成代码舞,跟着仙女姐姐一起蹦起来~视频来源:【紫颜】见过仙女蹦迪吗 【千盏】一、核心功能设计总体来说,我们需要分为以下几步完成:从B站上把小姐姐的视频下载下来对视频进行截取GIF,把截取的GIF通过ASCII Animator进行ASCII字符转换把转换的字符gif根据每
自定义ava数据集及训练与测试 完整版 时空动作/行为 视频数据集制作 yolov5, deep sort, VIA MMAction, SlowFast
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至2022年4月底。我已经将这篇博客的内容写为论文,上传至arxiv:https://arxiv.org/pdf/2204.10160.pdf欢迎大家指出我论文中的问题,特别是语法与用词问题在github上,我也上传了完整的项目:https://github.com/Whiffe/Custom-ava-dataset_Custom-Spatio-Temporally-Action-Video-Dataset关于自定义ava数据集,也是后台
【视频+源码】登录鉴权的三种方式:token、jwt、session实战分享
因为我既对接过session、cookie,也对接过JWT,今年因为工作需要也对接了gtoken的2个版本,对这方面的理解还算深入。尤其是看到官方文档评论区又小伙伴表示看不懂,所以做了这期视频内容出来:视频在这里:本期内容对应B站的开源视频因为涉及的知识点比较多,视频内容比较长。如果你觉得看视频浪费时间,可以直接阅读源码:goframe v2版本集成gtokengoframe v1版本集成gtokengoframe v2版本集成jwtgoframe v2版本session登录官方调用示例文档jwt和sess
【Android App】实战项目之仿微信的私信和群聊App附源码和演示视频 超详细必看
【Android App】实战项目之仿微信的私信和群聊App(附源码和演示视频 超详细必看)
采用MATLAB对正弦信号,语音信号进行生成、采样和恢复,利用MATLAB工具箱对混杂噪声的音频信号进行滤波
采用MATLAB对正弦信号,语音信号进行生成、采样和内插恢复,利用MATLAB工具箱对混杂噪声的音频信号进行滤波
Keras深度学习实战40——音频生成
随着移动互联网、云端存储等技术的快速发展,包含丰富信息的音频数据呈现几何级速率增长。这些海量数据在为人工分析带来困难的同时,也为音频认知、创新学习研究提供了数据基础。在本节中,我们通过构建生成模型来生成音频序列文件,从而进一步加深对序列数据处理问题的了解。
  • • 效率成吨提升之代码生成器-蓝湖工具神器…
  • • 【Audio音频开发】音频基础知识及PCM技…
  • • 见过仙女蹦迪吗?一起用python做个小仙…
  • • 【Android App】实战项目之仿抖音的短视…
  • • 自定义ava数据集及训练与测试 完整版 时…
  • • 【视频+源码】登录鉴权的三种方式:tok…
  • • 【Android App】实战项目之仿微信的私信…
  • • 零基础用Android Studio实现简单的本地…
  • • 采用MATLAB对正弦信号,语音信号进行生…
  • • Keras深度学习实战40——音频生成
  • • 视频实时行为检测——基于yolov5+deeps…
  • • 数电实验 数字电子钟设计 基于quartus …
  • • 腾讯会议使用OBS虚拟摄像头
  • • 文本生成视频Make-A-Video,根据一句话…
  • • 信号处理——MATLAB音频信号加噪、滤波
  • • 【新知实验室 - TRTC 实践】音视频互动…
  • • Keras深度学习实战39——音乐音频分类
  • • C++游戏game | 井字棋游戏坤坤版配资源…

Mastering Swift: essential details about strings的更多相关文章

  1. 为什么这个OpenGL ES 2.0着色器不能在iOS上使用我的VBO?

    如果有人能够了解这里出了什么问题,也许是对gl命令或其他一些不兼容的命令序列的错误排序,我将非常感谢你的帮助.尽管谷歌在“OpenGLES2.0编程指南”中进行了大量研究和研究,但我一直试图让这段代码整天都没有成功.我正在尝试在iPhone上的OpenGLES2.0中使用顶点缓冲区对象和自定义着色器.我试图交错来自以下类型的一系列自定义结构的顶点数据:位置,半径和颜色字节分别考虑顶点位置,点大小和

  2. ios – 将两个字符串转换为一组布尔值的快速方法是什么?

    我有一个长字符串,我想转换为一个布尔值数组.而且它需要很多次,很快.我天真的尝试是这样的:但这比我想要的要慢很多.我的剖析告诉我,地图是减速的地方,但我不知道我能做多么简单.我觉得如果没有Swift’s/ObjC的开销,这样做会很快.在C中,我认为这是一个简单的循环,其中一个字节的内存与一个常量进行比较,但我不知道我应该看的是什么函数或语法.有更好的办法吗?

  3. 在iOS上默认是char签名还是未签名?

    默认情况下,iOS上是否签名或未签名?(我认为这将是一个很好的回答问题,但奇怪的是谷歌没有任何用处!

  4. ios – 如何创建一个本机显示浮动窗口的ANE

    如何在Xcode中创建本机窗口并将其与MobileFlex应用程序集成.本机窗口应该与StageWebView组件类似,其中本机内容浮动在Flex应用程序的其余部分的矩形区域中.解决方法作为一名灵活的程序员,这是一个繁琐的过程,花了我几个星期才弄明白.希望这将有助于其他一些Xcode新手.首先,您必须对Objective-C和Xcode有基本的了解.您应该能够创建一个简单的HelloWorldXc

  5. Swift基础-0003

  6. Swift中如何转换不同类型的Mutable指针

    在Swift中我们拥有强大高级逻辑抽象能力的同时,低级底层操作被刻意的限制了.但是有些情况下我们仍然想做一些在C语言中的hack工作,下面本猫就带大家看一看如何做这样的事.hackingishappy!!!如上代码我们只要在闭包中返回一个Char指针就可以了,怎么做呢?这就需要借助另一个超级强大的方法unsafeBitCast,该方法将一种类型的变量内容强制转换为另一种,将以上闭包的//???这里不予解释,因为常玩汇编或C的小伙伴肯定早就了然于心鸟!

  7. Mastering Swift: essential details about strings

    https://rainsoft.io/mastering-swift-essential-details-about-strings/MasteringSwift:essentialdetailsaboutstringsDmitriPavlutin|05Oct2016Stringtypeisanimportantcomponentofanyprogramminglanguage.Themostu

  8. NSCharacterSet.characterIsMember()与Swift的字符类型

    想象一下,你有一个Swift的字符类型的实例,你想要确定它是否是一个NSCharacterSet的成员。NSCharacterSet的characterIsMember方法需要一个unichar,所以我们需要从Character到unichar。这可能是因为字符比unichar更通用,所以直接转换不会是安全的,但我只是猜测。我的理解是unichar是一个typealiasUInt16。因此,它不能被转换为单个unichar值,因为它可以由两个unichar组成。您可以通过将字符转换为字符串并使用utf16

  9. string – 如何将“Index”转换为Swift中的“Int”类型?

    尝试读取头文件,但是我找不到Index的类型,尽管它似乎符合使用方法的ForwardindexType协议。任何帮助是赞赏。您需要使用与原始字符串起始索引相关的distanceto方法:您还可以使用一种方法扩展字符串,以返回字符串中第一个出现的字符串,如下所示:Xcode8beta3Swift3

  10. string – 如何在Swift中将“Index”转换为“Int”类型?

    我想将字符串中包含的字母的索引转换为整数值.尝试读取头文件,但我找不到索引的类型,虽然它似乎符合协议ForwardindexType与方法(例如distanceto).任何帮助表示赞赏.您需要使用与原始字符串起始索引相关的distanceto(index)方法:您还可以使用方法扩展String以返回字符串中第一次出现的字符,如下所示:Xcode8Swift3Xcode9Swift4Swift4中另

随机推荐

  1. Swift UITextField,UITextView,UISegmentedControl,UISwitch

    下面我们通过一个demo来简单的实现下这些控件的功能.首先,我们拖将这几个控件拖到storyboard,并关联上相应的属性和动作.如图:关联上属性和动作后,看看实现的代码:

  2. swift UISlider,UIStepper

    我们用两个label来显示slider和stepper的值.再用张图片来显示改变stepper值的效果.首先,这三个控件需要全局变量声明如下然后,我们对所有的控件做个简单的布局:最后,当slider的值改变时,我们用一个label来显示值的变化,同样,用另一个label来显示stepper值的变化,并改变图片的大小:实现效果如下:

  3. preferredFontForTextStyle字体设置之更改

    即:

  4. Swift没有异常处理,遇到功能性错误怎么办?

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  5. 字典实战和UIKit初探

    ios中数组和字典的应用Applicationschedule类别子项类别名称优先级数据包contactsentertainment接触UIKit学习用Swift调用CocoaTouchimportUIKitletcolors=[]varbackView=UIView(frame:CGRectMake(0.0,0.0,320.0,CGFloat(colors.count*50)))backView

  6. swift语言IOS8开发战记21 Core Data2

    上一话中我们简单地介绍了一些coredata的基本知识,这一话我们通过编程来实现coredata的使用。还记得我们在coredata中定义的那个Model么,上面这段代码会加载这个Model。定义完方法之后,我们对coredata的准备都已经完成了。最后强调一点,coredata并不是数据库,它只是一个框架,协助我们进行数据库操作,它并不关心我们把数据存到哪里。

  7. swift语言IOS8开发战记22 Core Data3

    上一话我们定义了与coredata有关的变量和方法,做足了准备工作,这一话我们来试试能不能成功。首先打开上一话中生成的Info类,在其中引用头文件的地方添加一个@objc,不然后面会报错,我也不知道为什么。

  8. swift实战小程序1天气预报

    在有一定swift基础的情况下,让我们来做一些小程序练练手,今天来试试做一个简单地天气预报。然后在btnpressed方法中依旧增加loadWeather方法.在loadWeather方法中加上信息的显示语句:运行一下看看效果,如图:虽然显示出来了,但是我们的text是可编辑状态的,在storyboard中勾选Editable,再次运行:大功告成,而且现在每次单击按钮,就会重新请求天气情况,大家也来试试吧。

  9. 【iOS学习01】swift ? and !  的学习

    如果不初始化就会报错。

  10. swift语言IOS8开发战记23 Core Data4

    接着我们需要把我们的Rest类变成一个被coredata管理的类,点开Rest类,作如下修改:关键字@NSManaged的作用是与实体中对应的属性通信,BinaryData对应的类型是NSData,CoreData没有布尔属性,只能用0和1来区分。进行如下操作,输入类名:建立好之后因为我们之前写的代码有些地方并不适用于coredata,所以编译器会报错,现在来一一解决。

返回
顶部