cdub
cdub

Reputation: 25701

Loading the results set for Core Data fetch request

I have a variable declared as such:

private var theText = String()
private var aId = String()

I then do a fetch request and want to load it into that variable:

    let predicateA = NSPredicate(format: "active == %@", true as CVarArg);
    let predicateB = NSPredicate(format: "theId == %@", aId);
    let andPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: [predicateA, predicateB]);

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext;
    let requestData = NSFetchRequest<NSFetchRequestResult>(entityName: "DataTable");
    requestData.predicate = andPredicate;

    do
    {
        let results = try context.fetch(requestData);          

        dataactivitiesid = results.first

        // let resultset = results as! [NSManagedObject];

        /* for data in results
         {
         // let testyId: Any? = (data as AnyObject).value(forKey: "testyId");
         } */
    }
    catch
    {
        print("Error in fetching data");
    }

Do I need to loop through the result set like in the code that is commented above or since I know it is only one row being returned can I use .first? Thanks in advance.

Upvotes: 0

Views: 558

Answers (1)

vadian
vadian

Reputation: 285039

If you expect only one item you don't need a loop.

I recommend to optional bind the result of first to a variable which can be nil if no entry is found.

And you don't need a compound predicate, a single predicate can contain multiple conditions related to the same object. And finally this is not Objective-C, remove the trailing semicolons.

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext;
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "DataTable")
let predicate = NSPredicate(format: "active == TRUE AND theId == %@", aId)
fetchRequest.predicate = predicate

do {
    if let result = try context.fetch(fetchRequest).first  {      
        dataactivitiesid = result
    }

} catch {
    print(error) // print the actual error not a meaningless literal string
}

Upvotes: 2

Related Questions