- Swift CoreData
- 项目适配CodeData
- CoreData建数据库
- CoreData添加数据库属性
- CoreData 增
- CoreData 删
- CoreData 改
- CoreData 查
在Android中,一想到要操作SQLite,就觉得很繁琐;但是IOS中,有一套非常成熟的数据库API(接口)和GUI(图形用户界面),这样大大提升了用户体验,虽然,我们开发者,但是不可否认的是,我们也是一种另类的用户,一看到GUI,很多人可能更偏爱于IOS开发。
IOS数据库数据的增、删、改、查,其实也就是对NSManagedObjectContext的增、删、改、查。
项目适配CodeData
其实真的很简单,只需要你勾上User Core Data
这个选项即可。
然后你会看到项目中的AppDelegate.swift文件多了不少东西。其中也包括如下:
<code class="language-Swift hljs coffeescript has-numbering"> lazy <span class="hljs-reserved">var</span> <span class="hljs-attribute">persistentStoreCoordinator</span>: NSPersistentStoreCoordinator = {<span class="hljs-regexp">//</span> The persistent store coordinator <span class="hljs-keyword">for</span> the application. This implementation creates <span class="hljs-keyword">and</span> returns a coordinator, having added the store <span class="hljs-keyword">for</span> the application to it. This property <span class="hljs-keyword">is</span> optional since there are legitimate error conditions that could cause the creation <span class="hljs-keyword">of</span> the store to fail.<span class="hljs-regexp">//</span> Create the coordinator <span class="hljs-keyword">and</span> store<span class="hljs-reserved">let</span> coordinator = NSPersistentStoreCoordinator(<span class="hljs-attribute">managedObjectModel</span>: self.managedObjectModel)<span class="hljs-reserved">let</span> url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(<span class="hljs-string">"SingleViewCoreData.sqlite"</span>)<span class="hljs-regexp">//</span> 打印数据库文件存放目录NSLog(<span class="hljs-string">"\(url)"</span>)<span class="hljs-reserved">var</span> failureReason = <span class="hljs-string">"There was an error creating or loading the application's saved data."</span><span class="hljs-keyword">do</span> {<span class="hljs-keyword">try</span> coordinator.addPersistentStoreWithType(NSSQLiteStoreType, <span class="hljs-attribute">configuration</span>: nil, <span class="hljs-attribute">URL</span>: url, <span class="hljs-attribute">options</span>: nil)} <span class="hljs-keyword">catch</span> {<span class="hljs-regexp">//</span> Report any error we got.<span class="hljs-reserved">var</span> dict = [<span class="hljs-attribute">String</span>: AnyObject]()dict[NSLocalizedDescriptionKey] = <span class="hljs-string">"Failed to initialize the application's saved data"</span>dict[NSLocalizedFailureReasonErrorKey] = failureReasondict[NSUnderlyingErrorKey] = error as NSError<span class="hljs-reserved">let</span> wrappedError = NSError(<span class="hljs-attribute">domain</span>: <span class="hljs-string">"YOUR_ERROR_DOMAIN"</span>, <span class="hljs-attribute">code</span>: <span class="hljs-number">9999</span>, <span class="hljs-attribute">userInfo</span>: dict)<span class="hljs-regexp">//</span> Replace <span class="hljs-keyword">this</span> <span class="hljs-reserved">with</span> code to handle the error appropriately.<span class="hljs-regexp">//</span> abort() causes the application to generate a crash log <span class="hljs-keyword">and</span> terminate. You should <span class="hljs-keyword">not</span> use <span class="hljs-keyword">this</span> <span class="hljs-reserved">function</span> <span class="hljs-keyword">in</span> a shipping application, although it may be useful during development.NSLog(<span class="hljs-string">"Unresolved error \(wrappedError), \(wrappedError.userInfo)"</span>)abort()}<span class="hljs-keyword">return</span> coordinator}()lazy <span class="hljs-reserved">var</span> <span class="hljs-attribute">managedObjectContext</span>: NSManagedObjectContext = {<span class="hljs-regexp">//</span> Returns the managed object context <span class="hljs-keyword">for</span> the application (which <span class="hljs-keyword">is</span> already bound to the persistent store coordinator <span class="hljs-keyword">for</span> the application.) This property <span class="hljs-keyword">is</span> optional since there are legitimate error conditions that could cause the creation <span class="hljs-keyword">of</span> the context to fail.<span class="hljs-reserved">let</span> coordinator = self.persistentStoreCoordinator<span class="hljs-reserved">var</span> managedObjectContext = NSManagedObjectContext(<span class="hljs-attribute">concurrencyType</span>: .MainQueueConcurrencyType)managedObjectContext.persistentStoreCoordinator = coordinator<span class="hljs-keyword">return</span> managedObjectContext}()<span class="hljs-regexp">//</span> <span class="hljs-attribute">MARK</span>: - Core Data Saving supportfunc saveContext () {<span class="hljs-keyword">if</span> managedObjectContext.hasChanges {<span class="hljs-keyword">do</span> {<span class="hljs-keyword">try</span> managedObjectContext.save()} <span class="hljs-keyword">catch</span> {<span class="hljs-regexp">//</span> Replace <span class="hljs-keyword">this</span> implementation <span class="hljs-reserved">with</span> code to handle the error appropriately.<span class="hljs-regexp">//</span> abort() causes the application to generate a crash log <span class="hljs-keyword">and</span> terminate. You should <span class="hljs-keyword">not</span> use <span class="hljs-keyword">this</span> <span class="hljs-reserved">function</span> <span class="hljs-keyword">in</span> a shipping application, although it may be useful during development.<span class="hljs-reserved">let</span> nserror = error as NSErrorNSLog(<span class="hljs-string">"Unresolved error \(nserror), \(nserror.userInfo)"</span>)abort()}}}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li><li>52</li></ul>
我就是在看到let url
的时候,打印了url的路径。
CoreData建数据库
同样也是一个按钮!
点击Add Entity
后,然后点击建好的Entity选中后,按空格就可以修改数据库的名字了。
CoreData添加数据库属性
这里可以添加或者删除属性,也能修改属性的类型。
CoreData 增
数据库的任何操作都要涉及到(增、删、改、查)NSManagedObjectContext
对象。
通过这段代码能拿到本App的NSManagedObjectContext
(UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
获取添加新数据的NSManagedObject
NSEntityDescription.insertNewObjectForEntityForName(entityName: String, inManagedObjectContext context: NSManagedObjectContext) -> NSManagedObject
保存NSManagedObjectContext对象,不保存的话,什么都是扯淡
NSManagedObjectContext.save() throws
<code class="language-Swift hljs cs has-numbering"> <span class="hljs-comment">// 添加数据</span>func insert(){<span class="hljs-comment">// 获取NSManagedObjectContext对象</span><span class="hljs-keyword">let</span> context:NSManagedObjectContext = (UIApplication.sharedApplication().<span class="hljs-keyword">delegate</span> <span class="hljs-keyword">as</span>! AppDelegate).managedObjectContext<span class="hljs-comment">// 获取用于添加新Users表数据的NSManagedObject对象</span><span class="hljs-keyword">let</span> user:NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName(<span class="hljs-string">"Users"</span>, inManagedObjectContext: context)<span class="hljs-comment">// 添加name属性的值</span>user.setValue(<span class="hljs-string">"CaMnter"</span>, forKey: <span class="hljs-string">"name"</span>)<span class="hljs-comment">// 添加sign属性的值</span>user.setValue(<span class="hljs-string">"Save you from anything"</span>, forKey: <span class="hljs-string">"sign"</span>)<span class="hljs-comment">// 添加age属性的值</span>user.setValue(<span class="hljs-number">22</span>, forKey: <span class="hljs-string">"age"</span>)<span class="hljs-keyword">do</span>{<span class="hljs-comment">// NSManagedObjectContext对象保存</span><span class="hljs-keyword">try</span> context.save()}<span class="hljs-keyword">catch</span> <span class="hljs-keyword">let</span> error <span class="hljs-keyword">as</span> NSError{print(error.localizedDescription)}}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li></ul>
CoreData 删
删除NSManagedObject
NSManagedObjectContext.deleteObject(object: NSManagedObject)
<code class="language-Swift hljs php has-numbering"> <span class="hljs-comment">// 删除数据</span>func deleteNSManagedObject(indexPath: NSIndexPath){<span class="hljs-comment">// 通过NSManagedObject对象找到数据库的这条数据,并删除</span><span class="hljs-keyword">self</span>.context.deleteObject(<span class="hljs-keyword">self</span>.dataArr[indexPath.row] <span class="hljs-keyword">as</span>! NSManagedObject)<span class="hljs-keyword">do</span>{<span class="hljs-comment">// NSManagedObjectContext保存</span><span class="hljs-keyword">try</span> <span class="hljs-keyword">self</span>.context.save()}<span class="hljs-keyword">catch</span> let error <span class="hljs-keyword">as</span> NSError{<span class="hljs-keyword">print</span>(error.localizedDescription)}}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li></ul>
CoreData 改
其实也就是拿到对应要修改的NSManagedObject,然后重新对字段赋值。
<code class="language-Swift hljs php has-numbering"> <span class="hljs-comment">// 更新NSManagedObject对象</span>func updateNSManagedObject(obejct:NSManagedObject){<span class="hljs-comment">// 重新设置这个NSManagedObject上字段的值</span>obejct.setValue(<span class="hljs-keyword">self</span>.nameTV.text, forKey: <span class="hljs-string">"name"</span>)obejct.setValue(<span class="hljs-keyword">self</span>.signTV.text, forKey: <span class="hljs-string">"sign"</span>)<span class="hljs-keyword">do</span>{<span class="hljs-comment">// 获取NSManagedObject对应的NSManagedObjectContext,并保存</span><span class="hljs-keyword">try</span> <span class="hljs-keyword">self</span>.obejct.managedObjectContext?.save()}<span class="hljs-keyword">catch</span> let error <span class="hljs-keyword">as</span> NSError{NSLog(error.localizedDescription)}}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li></ul>
CoreData 查
CoreData查询数据的话,涉及到另外一个API**NSFetchRequest**。
NSFetchRequest的便利构造方法
NSFetchRequest:public convenience init(entityName: String)
通过NSFetchRequest查询对应表里的数据
NSManagedObjectContext.executeFetchRequest(request: NSFetchRequest) throws -> [AnyObject]
查询
<code class="language-Swift hljs php has-numbering"> <span class="hljs-keyword">var</span> dataArr:<span class="hljs-keyword">Array</span><AnyObject> = []<span class="hljs-keyword">var</span> context:NSManagedObjectContext!<span class="hljs-keyword">var</span> fetch:NSFetchRequest!override func viewDidLoad() {super.viewDidLoad()<span class="hljs-comment">// Uncomment the following line to preserve selection between presentations</span><span class="hljs-comment">// self.clearsSelectionOnViewWillAppear = false</span><span class="hljs-comment">// Uncomment the following line to display an Edit button in the navigation bar for this view controller.</span><span class="hljs-comment">// self.navigationItem.rightBarButtonItem = self.editButtonItem()</span><span class="hljs-comment">// 实例化NSManagedObjectContext对象</span><span class="hljs-keyword">self</span>.context = (UIApplication.sharedApplication().delegate <span class="hljs-keyword">as</span>! AppDelegate).managedObjectContext<span class="hljs-comment">// 实例化NSFetchRequest对象</span><span class="hljs-keyword">self</span>.fetch = NSFetchRequest(entityName: <span class="hljs-string">"Users"</span>)<span class="hljs-comment">// 开始查询</span><span class="hljs-keyword">self</span>.query()}<span class="hljs-comment">// 查询数据</span>func query(){<span class="hljs-keyword">do</span>{<span class="hljs-keyword">self</span>.dataArr = <span class="hljs-keyword">try</span> <span class="hljs-keyword">self</span>.context.executeFetchRequest(<span class="hljs-keyword">self</span>.fetch)}<span class="hljs-keyword">catch</span> let error <span class="hljs-keyword">as</span> NSError{<span class="hljs-keyword">print</span>(error.localizedDescription)}}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li></ul>
提取数据
<code class="language-Swift hljs cs has-numbering"> <span class="hljs-keyword">override</span> func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {<span class="hljs-keyword">let</span> cell = tableView.dequeueReusableCellWithIdentifier(<span class="hljs-string">"cell"</span>, forIndexPath: indexPath)<span class="hljs-comment">// Configure the cell...</span><span class="hljs-keyword">let</span> label = cell.viewWithTag(<span class="hljs-number">6</span>) <span class="hljs-keyword">as</span>! UILabel<span class="hljs-comment">// 提取对应数据</span><span class="hljs-keyword">let</span> <span class="hljs-keyword">object</span>:NSManagedObject = self.dataArr[indexPath.row] <span class="hljs-keyword">as</span>! NSManagedObject<span class="hljs-comment">// 根据字段提取数据</span><span class="hljs-keyword">let</span> name = <span class="hljs-keyword">object</span>.valueForKey(<span class="hljs-string">"name"</span>) <span class="hljs-keyword">as</span>! String<span class="hljs-keyword">let</span> sign = <span class="hljs-keyword">object</span>.valueForKey(<span class="hljs-string">"sign"</span>) <span class="hljs-keyword">as</span>! Stringlabel.text = <span class="hljs-string">"\(name):\(sign)"</span><span class="hljs-keyword">return</span> cell}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li></ul>