How to check if core data is empty
To check if the Core Database is empty you have to make a NSFetchRequest
on the entity you want to check, and check if the results of the request are empty.
You can check it with this function:
func entityIsEmpty(entity: String) -> Bool
{
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context = NSManagedObjectContext()
var request = NSFetchRequest(entityName: entity)
var error = NSErrorPointer()
var results:NSArray? = self.context.executeFetchRequest(request, error: error)
if let res = results
{
if res.count == 0
{
return true
}
else
{
return false
}
}
else
{
println("Error: \(error.debugDescription)")
return true
}
}
Or simplier and shorter solution: (using .countForFetchRequest
)
func entityIsEmpty(entity: String) -> Bool
{
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context = NSManagedObjectContext()
var request = NSFetchRequest(entityName: entity)
var error = NSErrorPointer()
var results:NSArray? = self.context.executeFetchRequest(request, error: error)
var count = context.countForFetchRequest(request, error: error)
if error != nil
{
println("Error: \(error.debugDescription)")
return true
}
else
{
if count == 0
{
return true
}
else
{
return false
}
}
}
How to check if CoreData is empty?
After the edit you messed up the code.
This checks if the fetched data array is empty and return
s if the array is empty
func entityIsEmpty()
{
let context = objAppDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<myEntity>(entityName: "myEntity")
do {
let result = try context.fetch(fetchRequest)
if result.isEmpty {
print("data not exist")
return
} else {
print("data exist")
}
for data in result {
var obj = userNSObj()
obj.myObject = data.myAttribute
myArray.append(obj)
}
} catch {
print(error)
}
}
Check if CoreData attribute is empty
That notification is for when the value is going to be accessed.
If I understand you correctly, you are not wanting to see if an entity exists, but an attribute within the entity. So, I assume you have it marked as an optional attribute.
Let's say you have a binary data attribute called rawData. If you want to find all the @"MyEntity" objects in the database that do not have any data set for this attribute, you cn issue this fetch request.
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"rawData = nil"];
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:0];
CoreData test if entity is null
You cannot catch something which does not throw an error. You need to improve the workflow.
Return the array and check for empty array after the call:
func recherche(code: String) -> [Vendeurs] {
let context=getContext(backGround: false)
let fetchRequest:NSFetchRequest<Vendeurs> = Vendeurs.fetchRequest()
let predicate:NSPredicate = NSPredicate(format: "code == %@", code)
fetchRequest.predicate = predicate
do {
return try context.fetch(fetchRequest)
} catch {
print(error)
return [Vendeurs]()
}
}
let vendeurs = v.recherche(code: codeSecret)
if !vendeurs.isEmpty, let vid = Int(vendeurs[0].id) {
if vid > 0 && vid != idVendeur {
// blah blah
}
}
Or make the recherche
method can throw
func recherche(code: String) -> [Vendeurs] throws {
let context=getContext(backGround: false)
let fetchRequest:NSFetchRequest<Vendeurs> = Vendeurs.fetchRequest()
let predicate:NSPredicate = NSPredicate(format: "code == %@", code)
fetchRequest.predicate = predicate
return try context.fetch(fetchRequest)
}
do {
let vendeurs = try v.recherche(code: codeSecret)
if !vendeurs.isEmpty, let vid = Int(vendeurs[0].id) {
if vid > 0 && vid != idVendeur {
// blah blah
}
}
} catch {
print(error)
}
Or – third option – if recherche
is supposed only to check and return an id > 0
func recherche(code: String) -> Int {
let context=getContext(backGround: false)
let fetchRequest:NSFetchRequest<Vendeurs> = Vendeurs.fetchRequest()
let predicate:NSPredicate = NSPredicate(format: "code == %@", code)
fetchRequest.predicate = predicate
do {
let result = try context.fetch(fetchRequest)
guard !result.isEmpty, let id = Int(result[0].id) else { return 0 }
return id
} catch {
print(error)
return 0
}
}
let vid = v.recherche(code: codeSecret)
if vid > 0 && vid != idVendeur {
// blah blah
}
}
How do I check if core data class is nil. in SWIFT
Line 3 of your code inserts a new Status
object, so each time this code is executed, you are adding an extra object. The newly inserted object will have a statusUpdate
of nil (most likely).
When you execute the fetch, in line 6, this new Status
object will be included in the results
, together with any objects you have saved previously. So when you iterate through all the results
, there will always be one for which statusUpdate
is nil.
I would restructure your code to do the fetch first, establish whether there are any results. If so, update the statusUpdate
; if not, create the new object and set the statusUpdate
field. Something like this:
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Status")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: &self.error)
if let resultsArray = results { // explicitly test for nil results
if resultsArray.count > 0 {
// count should be at most one, but just in case we will iterate through:
for result: AnyObject in resultsArray {
println("Current User fetched status from Core Data")
var newStatus = self.updateStatusText.text
result.setValue(newStatus, forKey: "statusUpdate")
}
else { // resultsArray is empty, so insert a new object
var newStatus = self.updateStatusText.text
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Status", inManagedObjectContext: context) as NSManagedObject
newUser.setValue(newStatus, forKey: "statusUpdate")
println("Status uploaded for the first time")
}
} else { // fetch returned nil, so log an error:
println("Nil returned by fetch")
}
context.save(&self.error)
Swift Core Data - handling empty fetch result
I would declare the function to return an optional and return nil when nothing is found
func returnStationType(stationTypeId: String) -> PersistantStationType? {
let context = container.viewContext
let request: NSFetchRequest<PersistantStationType> = PersistantStationType.fetchRequest()
request.predicate = NSPredicate(format: "%K == %@", #keyPath(PersistantStationType.stationId), stationTypeId)
do {
let result = try context.fetch(request)
if result.count != 0 {
return result[0]
} else {
print("4 Fetch result was empty for specified stationid: \(String(describing: stationTypeId))")
return nil
}
} catch {
print("Fetch on goal id: \(String(describing: stationTypeId)) failed. \(error)")
return nil
}
}
If on the error hand it is considered an error if more than one objects (or none) exists for an id then it would be better to throw an error in those situations
func returnStationType(stationTypeId: String) throws -> PersistantStationType {
let context = container.viewContext
let request: NSFetchRequest<PersistantStationType> = PersistantStationType.fetchRequest()
request.predicate = NSPredicate(format: "%K == %@", #keyPath(PersistantStationType.stationId), stationTypeId)
do {
let result = try context.fetch(request)
switch result.count {
case 0:
throw FetchError("No station type found for id \(stationTypeId)")
case 1:
return result[0]
default:
throw FetchError("Multiple station types found for id \(stationTypeId)")
}
} catch let error as NSError {
throw FetchError(error.localizedDescription)
}
}
struct FetchError: LocalizedError {
private let message: String
var errorDescription: String? {
message
}
init(_ message: String) {
self.message = message
}
}
Related Topics
Updating Fetchedresultscontroller for Predicate Set by Uisearchbar
Prevent Redirect Response with Alamofire in Swift
Swift: Overriding Typealias Inside Subclass
Swift Extension Storage for Protocols
How to Make Embedded View Controller Part of the Responder Chain
Can Not Conform to Protocol by Creating Extension with Where Clauses
Swift Pattern Matching with Enum and Optional Tuple Associated Values
Swift: Visual Glitches When Presenting a Main and Alternative (Login/Onboarding) Flow
iOS 11 PDFkit Not Updating Annotation Position
How to Test an Optionset with a Switch Statement
Draw Mkpointannotation with Title in Mksnapshot Image
Implicit Cast Function Receiving Tuple
Gmsplace Returns Invalid Coordinate (-180, -180), But Name and Place Id Are Correct
Countforfetchrequest in Swift 2.0
Passing and Storing Closures/Callbacks in Swift