Skip to content
This repository has been archived by the owner on Nov 24, 2021. It is now read-only.

Commit

Permalink
Prevent indexPath from being OoB (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
askeland authored and 3lvis committed Jan 30, 2017
1 parent a06dacb commit c77dc88
Showing 1 changed file with 7 additions and 9 deletions.
16 changes: 7 additions & 9 deletions Source/DATASource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -201,14 +201,19 @@ public class DATASource: NSObject {
- returns: The object at a given index path in the fetch results.
*/
public func object<T: NSManagedObject>(_ indexPath: IndexPath) -> T? {
if !self.isEmpty {
if !self.isEmpty && self.isIndexPathWithinBounds(indexPath) {
guard let object = self.fetchedResultsController.object(at: indexPath) as? T else { fatalError("Couldn't cast object") }
return object
}

return nil
}

private func isIndexPathWithinBounds(_ indexPath: IndexPath) -> Bool {
return self.fetchedResultsController.sections?.count ?? 0 > indexPath.section &&
self.fetchedResultsController.sections?[indexPath.section].numberOfObjects ?? 0 > indexPath.row
}

/**
Returns the index path of a given managed object.
- parameter object: An object in the receiver’s fetch results.
Expand Down Expand Up @@ -266,14 +271,7 @@ public class DATASource: NSObject {
- parameter indexPath: The indexPath where the cell is located.
*/
public func configure(_ cell: UIView, indexPath: IndexPath) {
var item: NSManagedObject?

let rowIsInsideBounds = (indexPath as NSIndexPath).row < self.count
if rowIsInsideBounds {
item = self.fetchedResultsController.object(at: indexPath) as? NSManagedObject
}

if let item = item {
if let item = self.objectAtIndexPath(indexPath) {
if let _ = self.tableView {
if let configuration = self.tableConfigurationBlock {
configuration(cell as! UITableViewCell, item, indexPath)
Expand Down

0 comments on commit c77dc88

Please sign in to comment.