最近在學習coredata, 因為項目開發中需要,特意學習和整理了一下,整理出來方便以后使用和同行借鑒。目前開發使用的swift語言開發的項目。所以整理出來的是swift版本,oc我就放棄了。 雖然swift3 已經有了,目前整理的這個版本是swift2 的。swift 3 的話有些新特性。 需要另外調整,后續有時間再整理。
繼承coredata有兩種方式:
創建項目時集成
這種方式是自動繼承在appdelegate里面,調用的使用需要通過uiapplication的方式來獲取appdelegate得到conext。本人不喜歡這種方式,不喜歡appdelegate太多代碼堆在一起,整理了一下這種方式
將coredata繼承的代碼單獨解耦出來做一個單例類
項目結構圖
項目文件說明
coredata核心的文件就是
1.xpstoremanager(管理coredata的單例類)
2.coredatademo.xcdatamodeld (coredata數據模型文件)
3.student+coredataproperites.swift和student.swift (學生對象)
4.viewcontroller.swift 和main.storyboard是示例代碼
細節代碼
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 "刪除" } } |
運行效果圖
源碼下載:coredatademo.zip
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/xiaopin/archive/2016/09/18/5883203.html