Reputation: 26107
In core data, I have an entity called "CachedRecipes" and in it an attribute called "jsonData".
I have a function to get JSON data from this attribute
func getJSONFromCoreData()->AnyObject {
var jsonDataInCoreData:AnyObject = ""
do
{
let fetchRequest = NSFetchRequest(entityName: "CachedRecipes")
let fetchedResults = try self.sharedContext.executeFetchRequest(fetchRequest)
for (var i=0; i < fetchedResults.count; i++)
{
let single_result = fetchedResults[i]
let out = single_result.valueForKey("jsonData")
print(out)
jsonDataInCoreData = out!
}
}
catch
{
print("error")
}
return jsonDataInCoreData
}
I am using a statement in viewDidLoad of the same UIViewController to get the data like this:
let jsonDataFromCoreData = self.getJSONFromCoreData()
How can I check if jsonDataFromCoreData
is empty or it doesn't have any key called jsonData
and that key doesn't have any value? I need to print out an error if it happens.
Upvotes: 0
Views: 458
Reputation: 4513
Change your function so it returns an optional
func getJSONFromCoreData()->AnyObject? {
var jsonDataInCoreData:AnyObject?
do
{
let fetchRequest = NSFetchRequest(entityName: "CachedRecipes")
let fetchedResults = try self.sharedContext.executeFetchRequest(fetchRequest)
for (var i=0; i < fetchedResults.count; i++)
{
let single_result = fetchedResults[i]
let out = single_result.valueForKey("jsonData")
print(out)
jsonDataInCoreData = out!
}
}
catch
{
print("error")
}
return jsonDataInCoreData
}
And if it returns nil
then it doesn't contain that data. You can just unwrap like this:
if let json = getJSONFromCoreData() {
// Has some data
} else {
// No data
}
Upvotes: 1