iOS CoreData 增删改查详解

时间:2022-09-20 11:26:51

最近在学习coredata, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴。目前开发使用的swift语言开发的项目。所以整理出来的是swift版本,oc我就放弃了。 虽然swift3 已经有了,目前整理的这个版本是swift2 的。swift 3 的话有些新特性。 需要另外调整,后续有时间再整理。 

继承coredata有两种方式: 

创建项目时集成

iOS CoreData 增删改查详解

这种方式是自动继承在appdelegate里面,调用的使用需要通过uiapplication的方式来获取appdelegate得到conext。本人不喜欢这种方式,不喜欢appdelegate太多代码堆在一起,整理了一下这种方式

将coredata继承的代码单独解耦出来做一个单例类 

项目结构图

iOS CoreData 增删改查详解

项目文件说明 
coredata核心的文件就是 
1.xpstoremanager(管理coredata的单例类) 
2.coredatademo.xcdatamodeld (coredata数据模型文件)
 3.student+coredataproperites.swift和student.swift (学生对象) 
4.viewcontroller.swift 和main.storyboard是示例代码

iOS CoreData 增删改查详解

细节代码 

1. xpstoremanager.swift
coredata数据管理单例类

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
//
 
// xpstoremanager.swift
 
// coredatademo
 
//
 
// created by xiaopin on 16/9/16.
 
// copyright © 2016年 xiaopin.cnblogs.com. all rights reserved.
 
//
 
 
 
import coredata
 
 
 
/// 本地数据库管理类:默认是写在appdelegate的,可以这样分离出来
 
class xpstoremanager {
 
 
 
 //单例写法
 
 static let shareinstance = xpstoremanager()
 
 
 
 private init() {
 
  
 
 }
 
 
 
 // mark: - core data stack
 
 
 
 lazy var applicationdocumentsdirectory: nsurl = {
 
  // the directory the application uses to store the core data store file. this code uses a directory named "com.pinguo.coredatademo" in the application's documents application support directory.
 
  let urls = nsfilemanager.defaultmanager().urlsfordirectory(.documentdirectory, indomains: .userdomainmask)
 
  print("\(urls[urls.count-1])")
 
  return urls[urls.count-1]
 
 }()
 
 
 
 lazy var managedobjectmodel: nsmanagedobjectmodel = {
 
  // the managed object model for the application. this property is not optional. it is a fatal error for the application not to be able to find and load its model.
 
  let modelurl = nsbundle.mainbundle().urlforresource("coredatademo", withextension: "momd")!
 
  return nsmanagedobjectmodel(contentsofurl: modelurl)!
 
 }()
 
 
 
 lazy var persistentstorecoordinator: nspersistentstorecoordinator = {
 
  // the persistent store coordinator for the application. this implementation creates and returns a coordinator, having added the store for the application to it. this property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
 
  // create the coordinator and store
 
  let coordinator = nspersistentstorecoordinator(managedobjectmodel: self.managedobjectmodel)
 
  let url = self.applicationdocumentsdirectory.urlbyappendingpathcomponent("singleviewcoredata.sqlite")
 
  var failurereason = "there was an error creating or loading the application's saved data."
 
  do {
 
   try coordinator.addpersistentstorewithtype(nssqlitestoretype, configuration: nil, url: url, options: nil)
 
  } catch {
 
   // report any error we got.
 
   var dict = [string: anyobject]()
 
   dict[nslocalizeddescriptionkey] = "failed to initialize the application's saved data"
 
   dict[nslocalizedfailurereasonerrorkey] = failurereason
 
   
 
   dict[nsunderlyingerrorkey] = error as nserror
 
   let wrappederror = nserror(domain: "your_error_domain", code: 9999, userinfo: dict)
 
   // replace this with code to handle the error appropriately.
 
   // abort() causes the application to generate a crash log and terminate. you should not use this function in a shipping application, although it may be useful during development.
 
   nslog("unresolved error \(wrappederror), \(wrappederror.userinfo)")
 
   abort()
 
  }
 
  
 
  return coordinator
 
 }()
 
 
 
 lazy var managedobjectcontext: nsmanagedobjectcontext = {
 
  // returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) this property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
 
  let coordinator = self.persistentstorecoordinator
 
  var managedobjectcontext = nsmanagedobjectcontext(concurrencytype: .mainqueueconcurrencytype)
 
  managedobjectcontext.persistentstorecoordinator = coordinator
 
  return managedobjectcontext
 
 }()
 
 
 
 // mark: - core data saving support
 
 
 
 func savecontext () {
 
  if managedobjectcontext.haschanges {
 
   do {
 
    try managedobjectcontext.save()
 
   } catch {
 
    // replace this implementation with code to handle the error appropriately.
 
    // abort() causes the application to generate a crash log and terminate. you should not use this function in a shipping application, although it may be useful during development.
 
    let nserror = error as nserror
 
    nslog("unresolved error \(nserror), \(nserror.userinfo)")
 
    abort()
 
   }
 
  }
 
 }
 
 
 
}

2.appdelegate.swift 

在这个行数中加入一句代码,退出后执行保存一下

?
1
2
3
4
5
6
func applicationwillterminate(application: uiapplication) {
  // called when the application is about to terminate. save data if appropriate. see also applicationdidenterbackground:.
  // saves changes in the application's managed object context before the application terminates.
  xpstoremanager.shareinstance.savecontext()
 
 }

3.student.swift 

编写了针对这个学生对象的增删改查 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//
 
// student.swift
 
// coredatademo
 
//
 
// created by cdmac on 16/9/12.
 
// copyright © 2016年 xiaopin.cnblogs.com. all rights reserved.
 
//
 
 
 
import foundation
 
import coredata
 
 
 
class student: nsmanagedobject {
 
 // insert code here to add functionality to your managed object subclass
 
 /*
 
  一般涉及到的情况有:增删改,单对象查询,分页查询(所有,条件查询,排序),对象是否存在,批量增加,批量修改
 
  */
 
 
 
 /// 判断对象是否存在, obj参数是当前属性的字典
 
 class func exsitsobject(obj:[string:string]) -> bool {
 
  
 
  //获取管理数据对象的上下文
 
  let context = xpstoremanager.shareinstance.managedobjectcontext
 
  //声明一个数据请求
 
  let fetchrequest = nsfetchrequest(entityname: "student")
 
  
 
  //组合过滤参数
 
  let stuid = obj["stuid"]
 
  let name = obj["name"]
 
  
 
  //方式一
 
  let predicate1 = nspredicate(format: "stuid = %@", stuid!)
 
  let predicate2 = nspredicate(format: "name = %@", name!)
 
  //合成过滤条件
 
  //or ,and, not , 意思是:或与非,懂数据库的同学应该就很容易明白
 
  let predicate = nscompoundpredicate(orpredicatewithsubpredicates: [predicate1,predicate2])
 
  //let predicate = nscompoundpredicate(andpredicatewithsubpredicates: [predicate1,predicate2])
 
  fetchrequest.predicate = predicate
 
  
 
  //方式二
 
  //fetchrequest.predicate = nspredicate(format: "stuid = %@ or name = %@", stuid!, name!)
 
  //fetchrequest.predicate = nspredicate(format: "stuid = %@ and name = %@", stuid!, name!)
 
  
 
  do{
 
   let fetchobjects:[anyobject]? = try context.executefetchrequest(fetchrequest)
 
   
 
   return fetchobjects?.count > 0 ? true : false
 
  }catch {
 
   fatalerror("exsitsobject \(error)")
 
  }
 
  
 
  return false
 
 }
 
 
 
 /// 添加对象, obj参数是当前属性的字典
 
 class func insertobject(obj: [string:string]) -> bool {
 
  
 
  //如果存在对象了就返回
 
  if exsitsobject(obj) {
 
   return false
 
  }
 
  
 
  //获取管理的数据上下文 对象
 
  let context = xpstoremanager.shareinstance.managedobjectcontext
 
  
 
  //创建学生对象
 
  let stu = nsentitydescription.insertnewobjectforentityforname("student",
 
                  inmanagedobjectcontext: context) as! student
 
 
 
  //对象赋值
 
  let sexstr:string
 
  if obj["sex"] == "男"{
 
   sexstr = "1"
 
  }else{
 
   sexstr = "0"
 
  }
 
  let numberfmt = nsnumberformatter()
 
  numberfmt.numberstyle = .nostyle
 
  stu.stuid = numberfmt.numberfromstring(obj["stuid"]!)
 
  stu.name = obj["name"]
 
  stu.createtime = nsdate()
 
  stu.sex = numberfmt.numberfromstring(sexstr)
 
  stu.classid = numberfmt.numberfromstring(obj["classid"]!)
 
  
 
  //保存
 
  do {
 
   try context.save()
 
   print("保存成功!")
 
   return true
 
  } catch {
 
   fatalerror("不能保存:\(error)")
 
  }
 
  return false
 
 }
 
 
 
 /// 删除对象
 
 class func deleteobject(obj:student) -> bool{
 
  
 
  //获取管理的数据上下文 对象
 
  let context = xpstoremanager.shareinstance.managedobjectcontext
 
  
 
  //方式一: 比如说列表已经是从数据库中获取的对象,直接调用coredata默认的删除方法
 
  context.deleteobject(obj)
 
  xpstoremanager.shareinstance.savecontext()
 
  
 
  //方式二:通过obj参数比如:id,name ,通过这样的条件去查询一个对象一个,把这个对象从数据库中删除
 
  //代码:略
 
  
 
  return true
 
 }
 
 
 
 /// 更新对象
 
 class func updateobject(obj:[string: string]) -> bool {
 
  //obj参数说明:当前对象的要更新的字段信息,唯一标志是必须的,其他的是可选属性
 
  let context = xpstoremanager.shareinstance.managedobjectcontext
 
  
 
  let oid = obj["stuid"]
 
  let student:student = self.fetchobjectbyid(int(oid!)!)! as! student
 
  
 
  //遍历参数,然后替换相应的参数
 
  let numberfmt = nsnumberformatter()
 
  numberfmt.numberstyle = .nostyle
 
  
 
  for key in obj.keys {
 
   switch key {
 
   case "name":
 
    student.name = obj["name"]
 
   case "classid":
 
    student.classid = numberfmt.numberfromstring(obj["classid"]!)
 
   default:
 
    print("如果有其他参数需要修改,类似")
 
   }
 
  }
 
  
 
  //执行更新操作
 
  do {
 
   try context.save()
 
   print("更新成功!")
 
   return true
 
  } catch {
 
   fatalerror("不能保存:\(error)")
 
  }
 
  
 
  return false
 
 }
 
 
 
  /// 查询对象
 
 class func fetchobjects(pageindex:int, pagesize:int) -> [anyobject]? {
 
  //获取管理的数据上下文 对象
 
  let context = xpstoremanager.shareinstance.managedobjectcontext
 
  
 
  //声明数据的请求
 
  let fetchrequest:nsfetchrequest = nsfetchrequest(entityname: "student")
 
  fetchrequest.fetchlimit = pagesize //每页大小
 
  fetchrequest.fetchoffset = pageindex * pagesize //第几页
 
  
 
  //设置查询条件:参考exsitsobject
 
  //let predicate = nspredicate(format: "id= '1' ", "")
 
  //fetchrequest.predicate = predicate
 
  
 
  //设置排序
 
  //按学生id降序
 
  let stuidsort = nssortdescriptor(key: "stuid", ascending: false)
 
  //按照姓名升序
 
  let namesort = nssortdescriptor(key: "name", ascending: true)
 
  let sortdescriptors:[nssortdescriptor] = [stuidsort,namesort]
 
  fetchrequest.sortdescriptors = sortdescriptors
 
  
 
  //查询操作
 
  do {
 
   let fetchedobjects:[anyobject]? = try context.executefetchrequest(fetchrequest)
 
   
 
   //遍历查询的结果
 
   /*
 
   for info:student in fetchedobjects as! [student]{
 
    print("id=\(info.stuid)")
 
    print("name=\(info.name)")
 
    print("sex=\(info.sex)")
 
    print("classid=\(info.classid)")
 
    print("createtime=\(info.createtime)")
 
    print("-------------------")
 
    
 
   }
 
    */
 
   return fetchedobjects
 
  }
 
  catch {
 
   fatalerror("不能保存:\(error)")
 
  }
 
  return nil
 
 }
 
 
 
  /// 根据id查询当个对象
 
 class func fetchobjectbyid(oid:int) -> anyobject?{
 
  
 
  //获取上下文对象
 
  let context = xpstoremanager.shareinstance.managedobjectcontext
 
  
 
  //创建查询对象
 
  let fetchrequest:nsfetchrequest = nsfetchrequest(entityname: "student")
 
  
 
  //构造参数
 
  fetchrequest.predicate = nspredicate(format: "stuid = %@", string(oid))
 
  
 
  //执行代码并返回结果
 
  do{
 
   let results:[anyobject]? = try context.executefetchrequest(fetchrequest)
 
   
 
   if results?.count > 0 {
 
    return results![0]
 
   }
 
  }catch{
 
   fatalerror("查询当个对象致命错误:\(error)")
 
  }
 
  
 
  return nil
 
 }
 
}

4.viewcontroller.swift 

具体使用: 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//
 
// viewcontroller.swift
 
// coredatademo
 
//
 
// created by cdmac on 16/9/11.
 
// copyright © 2016年 pinguo. all rights reserved.
 
//
 
 
 
import uikit
 
 
 
let cellidentifiler = "reusecell"
 
 
 
class viewcontroller: uiviewcontroller {
 
 @iboutlet weak var txtno: uitextfield!
 
 @iboutlet weak var txtname: uitextfield!
 
 @iboutlet weak var txtsex: uitextfield!
 
 @iboutlet weak var txtclassid: uitextfield!
 
 @iboutlet weak var tableview: uitableview!
 
 var dataarray:[anyobject]?
 
 
 
 override func viewdidload() {
 
  super.viewdidload()
 
  // do any additional setup after loading the view, typically from a nib.
 
  self.dataarray = student.fetchobjects(0, pagesize: 20)
 
  self.tableview.reloaddata()
 
 }
 
 
 
 override func didreceivememorywarning() {
 
  super.didreceivememorywarning()
 
  // dispose of any resources that can be recreated.
 
 }
 
 
 
 
 
 @ibaction func addaction(sender: anyobject) {
 
 
 
  var dic = [string:string]()
 
  
 
  dic["stuid"] = txtno.text
 
  dic["name"] = txtname.text
 
  dic["sex"] = txtsex.text
 
  dic["classid"] = txtclassid.text
 
  
 
  if student.insertobject(dic) {
 
   print("添加成功")
 
   self.dataarray = student.fetchobjects(0,pagesize: 20)
 
   
 
   self.tableview.reloaddata()
 
  }else{
 
   print("添加失败")
 
  }
 
 }
 
 
 
 @ibaction func updateaction(sender: anyobject) {
 
  
 
  var dic = [string:string]()
 
  
 
  dic["stuid"] = txtno.text
 
  dic["name"] = txtname.text
 
  //dic["sex"] = txtsex.text
 
  dic["classid"] = txtclassid.text
 
  
 
  if student.updateobject(dic) {
 
   print("更新成功")
 
   self.dataarray = student.fetchobjects(0,pagesize: 20)
 
   
 
   self.tableview.reloaddata()
 
  }else{
 
   print("更新失败")
 
  }
 
  
 
 }
 
 
 
}
 
 
 
extension viewcontroller:uitableviewdelegate,uitableviewdatasource{
 
 
 
 //表格有多少组
 
 func numberofsectionsintableview(tableview: uitableview) -> int {
 
  return 1
 
 }
 
 
 
 //每组多少行
 
 func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int {
 
  if self.dataarray != nil && self.dataarray?.count > 0 {
 
   return self.dataarray!.count
 
  }
 
  return 0
 
 }
 
 
 
 //高度
 
 func tableview(tableview: uitableview, heightforrowatindexpath indexpath: nsindexpath) -> cgfloat {
 
  return 50
 
 }
 
 
 
 //单元格加载
 
 func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell {
 
  let cell = tableview.dequeuereusablecellwithidentifier(cellidentifiler)
 
  
 
  let stu:student = self.dataarray![indexpath.row] as! student
 
  
 
  let label1:uilabel = cell?.contentview.viewwithtag(10001) as! uilabel
 
  let label2:uilabel = cell?.contentview.viewwithtag(10002) as! uilabel
 
  var sexstr = "男"
 
  if stu.sex?.intvalue != 1 {
 
   sexstr = "女"
 
  }
 
  label1.text = "\(stu.stuid!) \(stu.name!) \(sexstr) \(stu.classid!)"
 
  label2.text = "http://xiaopin.cnblogs.com"
 
  
 
  return cell!
 
 }
 
 
 
 //选中
 
 func tableview(tableview: uitableview, didselectrowatindexpath indexpath: nsindexpath) {
 
  
 
 }
 
 
 
 func tableview(tableview: uitableview, caneditrowatindexpath indexpath: nsindexpath) -> bool {
 
  return true
 
 }
 
 
 
 func tableview(tableview: uitableview, commiteditingstyle editingstyle: uitableviewcelleditingstyle, forrowatindexpath indexpath: nsindexpath) {
 
  if editingstyle == .delete {
 
   //获取当前对象
 
   let student:student = self.dataarray![indexpath.row] as! student
 
   
 
   //删除本地存储
 
   student.deleteobject(student)
 
   
 
   //刷新数据源
 
   self.dataarray?.removeatindex(indexpath.row)
 
   //self.dataarray = student.fetchobjects(0, pagesize: 20)
 
   
 
   //删除单元格
 
   tableview.deleterowsatindexpaths([indexpath], withrowanimation: .automatic)
 
  }
 
 }
 
 
 
 func tableview(tableview: uitableview, editingstyleforrowatindexpath indexpath: nsindexpath) -> uitableviewcelleditingstyle {
 
  return .delete
 
 }
 
 
 
 func tableview(tableview: uitableview, titlefordeleteconfirmationbuttonforrowatindexpath indexpath: nsindexpath) -> string? {
 
  return "删除"
 
 }
 
}

运行效果图

iOS CoreData 增删改查详解

源码下载:coredatademo.zip

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/xiaopin/archive/2016/09/18/5883203.html