Skip to content
This repository was archived by the owner on Sep 15, 2025. It is now read-only.

Commit 096588f

Browse files
committed
Refatorano nome da entidade "Itens" para Item, os Models devem ser vistos como entidades e não como tabelas.
1 parent dc05b6c commit 096588f

File tree

7 files changed

+132
-122
lines changed

7 files changed

+132
-122
lines changed

Item.swift

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
//
2+
// Itens.swift
3+
// ListaCoreData
4+
//
5+
// Created by Diego Rossini Vieira on 8/27/15.
6+
// Copyright (c) 2015 Diego Rossini Vieira. All rights reserved.
7+
//
8+
9+
import Foundation
10+
import CoreData
11+
12+
// MODEL para abstração dos dados
13+
class Item: NSManagedObject {
14+
15+
/// mapeamento do campo "nome" para String
16+
@NSManaged var nome: String
17+
18+
/// Função para adicionar um item do CoreData de forma rápida
19+
///
20+
/// :param: objectContext Conexão com o CoreData
21+
/// :param: nome Nome para salvar
22+
///
23+
class func criaNovoObjeto(objectContext: NSManagedObjectContext, nome: String) -> Item {
24+
let newItem = NSEntityDescription.insertNewObjectForEntityForName("Item", inManagedObjectContext: objectContext) as! Item
25+
26+
// fazendo o as! Item, não precisamos criar o objeto usando setValue, o que simplifica o processo
27+
newItem.nome = nome
28+
29+
return newItem
30+
}
31+
32+
/// Função para buscar todos os dados do CoreData
33+
///
34+
/// :param: managedObjectContext contexto a ser manipulado
35+
///
36+
class func buscarTodos(managedObjectContext: NSManagedObjectContext) -> [Item] {
37+
let listagemCoreData = NSFetchRequest(entityName: "Item")
38+
39+
// ordena os resultados alfabetica pelo campo "nome"
40+
let orderByName = NSSortDescriptor(key: "nome", ascending: true, selector: "caseInsensitiveCompare:")
41+
42+
// define o filtro de ordenação
43+
listagemCoreData.sortDescriptors = [orderByName]
44+
45+
// executa a busca e retorna os valores no array itens
46+
return managedObjectContext.executeFetchRequest(listagemCoreData, error: nil) as? [Item] ?? []
47+
}
48+
49+
/// Função para encontrar um Item por nome
50+
///
51+
/// :param: nome Nome do item para buscar
52+
/// :param: managedObjectContext contexto a ser manipulado
53+
///
54+
class func buscar(nome: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> Item? {
55+
let fetchRequest = NSFetchRequest(entityName: "Item")
56+
fetchRequest.predicate = NSPredicate(format: "nome = %@", nome)
57+
58+
let result = managedObjectContext.executeFetchRequest(fetchRequest, error: nil) as? [Item]
59+
return result?.first
60+
}
61+
62+
/// Função para verificar se já existe um registro com esse nome
63+
///
64+
/// :param: nome Nome do item para buscar
65+
/// :param: managedObjectContext contexto a ser manipulado
66+
///
67+
class func itemExistente(nome: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> Bool {
68+
return buscar(nome, inManagedObjectContext: managedObjectContext) != nil
69+
}
70+
71+
// MARK: - Init
72+
73+
convenience init(nome: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) {
74+
let entity = NSEntityDescription.entityForName("Item", inManagedObjectContext: managedObjectContext)!
75+
self.init(entity: entity, insertIntoManagedObjectContext: managedObjectContext)
76+
self.nome = nome
77+
}
78+
79+
// MARK: -
80+
81+
/// Função para apagar um item do CoreData
82+
///
83+
/// :param: managedObjectContext contexto a ser manipulado
84+
///
85+
func apagar(managedObjectContext: NSManagedObjectContext) {
86+
managedObjectContext.deleteObject(self)
87+
}
88+
89+
/// Função para salvar os dados no CoreData
90+
///
91+
/// :param: managedObjectContext contexto a ser manipulado
92+
///
93+
func salvar(managedObjectContext: NSManagedObjectContext) {
94+
var error: NSErrorPointer = nil
95+
96+
// se a ação salvar falhar, imprime erro
97+
if(managedObjectContext.save(error)) {
98+
if (error != nil) {
99+
println("Erro ao salvar: \(error.debugDescription)")
100+
}
101+
}
102+
}
103+
}

ListaCoreData.xcodeproj/project.pbxproj

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
9646CAF61B8E8B60003FF188 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9646CAF51B8E8B60003FF188 /* Images.xcassets */; };
1515
9646CAF91B8E8B60003FF188 /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9646CAF71B8E8B60003FF188 /* LaunchScreen.xib */; };
1616
9646CB051B8E8B61003FF188 /* ListaCoreDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9646CB041B8E8B61003FF188 /* ListaCoreDataTests.swift */; };
17-
96D974FC1B8F4212008C4F72 /* Itens.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96D974FB1B8F4212008C4F72 /* Itens.swift */; };
17+
96535AC61B8FE78F009402B7 /* Item.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96535AC51B8FE78F009402B7 /* Item.swift */; };
1818
96EB560B1B8F61240059EB1B /* README.md in Resources */ = {isa = PBXBuildFile; fileRef = 96EB560A1B8F61240059EB1B /* README.md */; };
1919
/* End PBXBuildFile section */
2020

@@ -40,7 +40,7 @@
4040
9646CAFE1B8E8B61003FF188 /* ListaCoreDataTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = ListaCoreDataTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
4141
9646CB031B8E8B61003FF188 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
4242
9646CB041B8E8B61003FF188 /* ListaCoreDataTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ListaCoreDataTests.swift; sourceTree = "<group>"; };
43-
96D974FB1B8F4212008C4F72 /* Itens.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Itens.swift; sourceTree = "<group>"; };
43+
96535AC51B8FE78F009402B7 /* Item.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Item.swift; path = ../Item.swift; sourceTree = "<group>"; };
4444
96EB560A1B8F61240059EB1B /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = "<group>"; };
4545
/* End PBXFileReference section */
4646

@@ -84,7 +84,7 @@
8484
9646CAE81B8E8B60003FF188 /* ListaCoreData */ = {
8585
isa = PBXGroup;
8686
children = (
87-
96D974FB1B8F4212008C4F72 /* Itens.swift */,
87+
96535AC51B8FE78F009402B7 /* Item.swift */,
8888
9646CAEB1B8E8B60003FF188 /* AppDelegate.swift */,
8989
9646CAF01B8E8B60003FF188 /* ViewController.swift */,
9090
9646CAF21B8E8B60003FF188 /* Main.storyboard */,
@@ -222,8 +222,8 @@
222222
isa = PBXSourcesBuildPhase;
223223
buildActionMask = 2147483647;
224224
files = (
225+
96535AC61B8FE78F009402B7 /* Item.swift in Sources */,
225226
9646CAF11B8E8B60003FF188 /* ViewController.swift in Sources */,
226-
96D974FC1B8F4212008C4F72 /* Itens.swift in Sources */,
227227
9646CAEF1B8E8B60003FF188 /* ListaCoreData.xcdatamodeld in Sources */,
228228
9646CAEC1B8E8B60003FF188 /* AppDelegate.swift in Sources */,
229229
);

ListaCoreData.xcodeproj/project.xcworkspace/xcshareddata/ListaCoreData.xccheckout

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,26 @@
1010
<string>ListaCoreData</string>
1111
<key>IDESourceControlProjectOriginsDictionary</key>
1212
<dict>
13+
<key>121D04B38A530B0284E3C6519D577BBE40F7D3E2</key>
14+
<string>github.com:diegorv/iOS-Swift-TableView-CoreData-Example.git</string>
1315
<key>5000B6892E1DBFEB3F3375ACCCCA32A3C121FBDE</key>
1416
<string>github.com:diegorv/iOS-Swift-TableView-CoreData-Example.git</string>
1517
</dict>
1618
<key>IDESourceControlProjectPath</key>
1719
<string>ListaCoreData.xcodeproj</string>
1820
<key>IDESourceControlProjectRelativeInstallPathDictionary</key>
1921
<dict>
20-
<key>5000B6892E1DBFEB3F3375ACCCCA32A3C121FBDE</key>
22+
<key>121D04B38A530B0284E3C6519D577BBE40F7D3E2</key>
2123
<string>../..</string>
24+
<key>5000B6892E1DBFEB3F3375ACCCCA32A3C121FBDE</key>
25+
<string>../../../ListaCoreData</string>
2226
</dict>
2327
<key>IDESourceControlProjectURL</key>
2428
<string>github.com:diegorv/iOS-Swift-TableView-CoreData-Example.git</string>
2529
<key>IDESourceControlProjectVersion</key>
2630
<integer>111</integer>
2731
<key>IDESourceControlProjectWCCIdentifier</key>
28-
<string>5000B6892E1DBFEB3F3375ACCCCA32A3C121FBDE</string>
32+
<string>121D04B38A530B0284E3C6519D577BBE40F7D3E2</string>
2933
<key>IDESourceControlProjectWCConfigurations</key>
3034
<array>
3135
<dict>
@@ -36,6 +40,14 @@
3640
<key>IDESourceControlWCCName</key>
3741
<string>ListaCoreData</string>
3842
</dict>
43+
<dict>
44+
<key>IDESourceControlRepositoryExtensionIdentifierKey</key>
45+
<string>public.vcs.git</string>
46+
<key>IDESourceControlWCCIdentifierKey</key>
47+
<string>121D04B38A530B0284E3C6519D577BBE40F7D3E2</string>
48+
<key>IDESourceControlWCCName</key>
49+
<string>TableView-CoreData-Example</string>
50+
</dict>
3951
</array>
4052
</dict>
4153
</plist>

ListaCoreData/Itens.swift

Lines changed: 0 additions & 105 deletions
This file was deleted.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
22
<model userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="7701" systemVersion="14F27" minimumToolsVersion="Automatic" macOSVersion="Automatic" iOSVersion="Automatic">
3-
<entity name="Itens" representedClassName="ListaCoreData.Itens" syncable="YES">
3+
<entity name="Item" representedClassName="ListaCoreData.Item" syncable="YES">
44
<attribute name="nome" optional="YES" attributeType="String" syncable="YES"/>
55
</entity>
66
<elements>
7-
<element name="Itens" positionX="-63" positionY="-18" width="128" height="60"/>
7+
<element name="Item" positionX="-63" positionY="-18" width="128" height="60"/>
88
</elements>
99
</model>

ListaCoreData/ViewController.swift

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class ViewController: UIViewController, UITableViewDataSource {
1616
let coreDataDB = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
1717

1818
/// Array de itens do sistema
19-
var itens = [Itens]()
19+
var itens = [Item]()
2020

2121
// MARK: - Outlets
2222

@@ -33,7 +33,7 @@ class ViewController: UIViewController, UITableViewDataSource {
3333
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
3434

3535
// carrega os dados do CoreData
36-
itens = Itens.buscarTodos(coreDataDB)
36+
itens = Item.buscarTodos(coreDataDB)
3737
}
3838

3939
// MARK: - Actions
@@ -50,7 +50,7 @@ class ViewController: UIViewController, UITableViewDataSource {
5050
self.alertaError("Erro ao salvar item", msg: "O nome do item não pode ficar em branco")
5151
}
5252
// Verifica se o item já existe
53-
else if (Itens.itemExistente(nomeAdicionar, inManagedObjectContext: self.coreDataDB)) {
53+
else if (Item.itemExistente(nomeAdicionar, inManagedObjectContext: self.coreDataDB)) {
5454
self.alertaError("Erro ao salvar item", msg: "Já existe um item com o nome: \(nomeAdicionar) \n Não é possível salvar dois nomes iguais")
5555
}
5656
// Salva no CoreData
@@ -87,7 +87,7 @@ class ViewController: UIViewController, UITableViewDataSource {
8787
/// teoricamente seria melhor não fazer isso.
8888
func adicionaItem(tableView: UITableView, nome: String) {
8989
// chama uma função da classe "Itens" que já faz o processo de criar o novo objeto do CoreData
90-
var novoItem = Itens(nome: nome, inManagedObjectContext: coreDataDB)
90+
var novoItem = Item(nome: nome, inManagedObjectContext: coreDataDB)
9191

9292
// adiciona no final do array de itens o novo item
9393
itens.append(novoItem)
@@ -96,7 +96,7 @@ class ViewController: UIViewController, UITableViewDataSource {
9696
novoItem.salvar(coreDataDB)
9797

9898
// recarrega os itens, se deixar descomentado essa linha aqui, ele vai adicionar o item na tableView na ordem alfabetica
99-
itens = Itens.buscarTodos(coreDataDB)
99+
itens = Item.buscarTodos(coreDataDB)
100100

101101
// recarrega a TableView
102102
tableView.reloadData()
@@ -159,18 +159,18 @@ class ViewController: UIViewController, UITableViewDataSource {
159159
true
160160
}
161161
// Verifica se o novo nome já existe
162-
else if (Itens.itemExistente(novoNome, inManagedObjectContext: self.coreDataDB)) {
162+
else if (Item.itemExistente(novoNome, inManagedObjectContext: self.coreDataDB)) {
163163
self.alertaError("Erro ao salvar item", msg: "Já existe um item com o nome: \(novoNome) \n Não é possível salvar dois nomes iguais")
164164
}
165165
// Salva no CoreData
166166
else {
167167
// Chama a função para atualizar o nome
168-
let item = Itens.buscar(nomeAtual, inManagedObjectContext: self.coreDataDB)
168+
let item = Item.buscar(nomeAtual, inManagedObjectContext: self.coreDataDB)
169169
item?.nome = novoNome
170170
item?.salvar(self.coreDataDB)
171171

172172
// Racarrega os dados no CoreData
173-
self.itens = Itens.buscarTodos(self.coreDataDB)
173+
self.itens = Item.buscarTodos(self.coreDataDB)
174174

175175
// Recarrega a TableView
176176
self.tableView.reloadData()
@@ -208,7 +208,7 @@ class ViewController: UIViewController, UITableViewDataSource {
208208
// A TableView sempre carrega os elementos do array "itens" que são os dados do CoreData
209209
// Se você deleta um item do coreData e não recarrega o array, a quantidade de elementos do Array é diferente da quantidade das linhas
210210
// do tableView e dá erro
211-
self.itens = Itens.buscarTodos(self.coreDataDB)
211+
self.itens = Item.buscarTodos(self.coreDataDB)
212212

213213
// Remove o item da TableView
214214
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

0 commit comments

Comments
 (0)