Fetch a specific single core data item with in the set

In my swift code below I am attempting to fetch a core data item from the set of core data. I want to fetch the 3 item in the core data set. So the 3rd oldest item in the core data set. Assume there is a 3 item. I have my view controller class and my help class. Don’t know how to use the fetch function to successfully do this. Put the 3rd item on my image view please thanks.

VIEW CONTROLLER CLASS

     var fetchImageView = UIImageView()
override func viewDidLoad() {
        super.viewDidLoad()

    let gwen = UIImage(named: "f.jpeg")
    if let imageData = gwen.self?.pngData() {
        DataBaseHelper.shareInstance.saveImage(data: imageData)
    }

    print( "Hello",DataBaseHelper.shareInstance.fetchImage().count)


    getImage(imageNo: 1)
    }

 func getImage(imageNo:Int) {
   // first check the array bounds
   let info = DataBaseHelper.shareInstance.fetchImage()
   if info.count > imageNo {
       // check if the data is available
       if let imageData = info[imageNo].img {
           fetchImageView.image = UIImage(data: imageData)
       } else {
           // no data
           print("data is empty")
       }
   } else {
       // image number is greater than array bounds
       print("you are asking out of bounds")
   }
 }

HELPER CLASS

class DataBaseHelper {

static let shareInstance = DataBaseHelper()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

func saveImage(data: Data) {
    let imageInstance = Info(context: context)
    imageInstance.img = data
        
    do {
        try context.save()
        print("Image is saved")
    } catch {
        print(error.localizedDescription)
    }
}

func fetchImage() -> [Info] {
    
  
    var fetchingImage = [Info]()
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Info")
    
    do {
        
        fetchingImage = try context.fetch(fetchRequest) as! [Info]
    } catch {
        print("Error while fetching the image")
    }
    
    return fetchingImage
}

This topic was automatically closed after 166 days. New replies are no longer allowed.