Here is my code. I have extra entities with nil attributes in Core Data. when I delete and run application firstly, I get one saved object with nil attributes fetched from core data.
class RepositoryEntity {
private var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func fetchRepositories() -> [RepositoryEntity] {
do {
return try context.fetch(RepositoryEntity.fetchRequest())
} catch(let error) {
print("errr: ", error.localizedDescription)
}
return []
}
func saveObject(repo: Repository, onSuccess: () -> Void, onFailure: (_ error: String) -> Void) {
let repoEntity = RepositoryEntity(context: self.context)
repoEntity.fullName = repo.fullName
repoEntity.dateCreated = repo.dateCreated
repoEntity.url = repo.url
repoEntity.language = repo.language
repoEntity.repoDescription = repo.repoDescription
repoEntity.id = repo.id
let ownerEntity = OwnerEntity(context: self.context)
ownerEntity.ownerName = repo.owner.ownerName
ownerEntity.avatarUrl = repo.owner.avatarUrl
repoEntity.addToOwner(ownerEntity)
// Save the data
do {
try context.save()
onSuccess()
} catch(let error) {
onFailure("Something Happend. Try again later.")
print(error.localizedDescription)
}
}
func deleteRepository(repo: Repository, onSuccess: () -> Void, onFailure: (_ error: String) -> Void) {
let repositories = fetchRepositories()
guard let deletableRepo = repositories.first(where: {$0.id == repo.id}) else { return }
self.context.delete(deletableRepo)
do {
try context.save()
onSuccess()
} catch(let error) {
onFailure("Something Happens. try again later.")
print(error.localizedDescription)
}
}
}
when I delete and run application firstly, I get one saved object with nil attributes fetched from core data.
CodePudding user response:
When you write "I get one saved object...": what object? RepositoryEntity
? How do you know you have a saved object, by calling fetchRepositories()
? I can only assume it's like that (as opposed to having an empty OwnerEntity
).
In that case, the problem is that, to call func fetchRepositories()
you need to create an instance. So, when you start with zero objects, as soon as you call fetchRepositories()
you already have at least one.
Change:
func fetchRepositories() -> [RepositoryEntity]
with:
static func fetchRepositories() -> [RepositoryEntity]
and call it from the type:
RepositoryEntity.fetchRepositories()
The same also for deleteRepository
.