Saturday, September 20, 2014

NSFetchedResultsController in Swift


NSFetchedResultsController in Swift


    lazy var fetchedResultsController: NSFetchedResultsController = {
        let moc = CoreDataTools.sharedInstance.managedObjectContext!
        let entity = NSEntityDescription.entityForName("Certificate", inManagedObjectContext: moc)
        
        let fetchRequest = NSFetchRequest(entityName: NSStringFromClass(Certificate))
        fetchRequest.entity = entity
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
        
        var frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
        var error: NSError? = nil
        frc.performFetch(&error)
        if let e = error {
            println("Error was \(e)")
        }
        return frc

    }()

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        var count = 0
        if let s = self.fetchedResultsController.sections as? [NSFetchedResultsSectionInfo] {
            count = s[section].numberOfObjects
        }
        return count

    }


    lazy var collectionView: UICollectionView = {
        var layoutView = UICollectionViewFlowLayout()
        layoutView.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10)
        layoutView.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layoutView.itemSize = CGSizeMake(100, 100)
        layoutView.minimumLineSpacing = 10
        layoutView.minimumInteritemSpacing = 5
        var colView = UICollectionView(frame: CGRectZero, collectionViewLayout: layoutView)
        colView.setTranslatesAutoresizingMaskIntoConstraints(false)
        colView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "CertificationCellReuse")
        colView.delegate = self
        colView.dataSource = self
        colView.backgroundColor = ThemeFactory.sharedInstance.appSecondaryColor()
        colView.bounces = true
        colView.alwaysBounceHorizontal = true
        colView.scrollIndicatorInsets = UIEdgeInsetsMake(0,0,3,0)
        colView.indicatorStyle = UIScrollViewIndicatorStyle.Black
        return colView

    }()

No comments:

Post a Comment