Code Monkey home page Code Monkey logo

pagedarray's Introduction

PagedArray

Version License Platform

PagedArray is a generic Swift data structure for helping you implement paging mechanisms in (but not limited to) UITableViews, UICollectionViews and UIPageViewControllers.

It is a Swift-version of its Objective-C equivalent AWPagedArray, which was used for implementing the techniques described in the blog post Fluent Pagination โ€“ no more jumpy scrolling.

PagedArray represents a list of optional elements stored by pages. It implements all the familiar Swift collection protocols so your datasource can use it just like a regular Array while providing an easy-to-use API for setting pages of data as they are retrieved.

// Initialize
var pagedArray = PagedArray<String>(count: 200, pageSize: 20)

// Set data pages
pagedArray.set(elements: ["A" ... "T"], forPage: 1)

// Retrieve data like a normal array containing optional elements
pagedArray.count // 200
pagedArray[0] // "A"
pagedArray[100] // nil

// Iterate
for element: String? in pagedArray {
    // Do magic
}

// Map, filter reduce
pagedArray.filter{ $0 != nil }.map{ $0! }.reduce("", combine:+) // "ABCDE..."

// Convert to array
Array(pagedArray) // ["A", "B", ... nil, nil]

UITableView example

Installation

Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks.

To use PagedArray with a project targeting iOS 7, you must include the PagedArray.swift source file directly in your project.

Swift Package Manager

To integrate PagedArray into your project using SwiftPM add the following to your Package.swift:

dependencies: [
  .package(url: "https://github.com/MrAlek/PagedArray", from: "0.9"),
],

Cocoapods

To integrate PagedArray into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'

pod 'PagedArray'

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate PagedArray into your Xcode project using Carthage, specify it in your Cartfile:

github "MrAlek/PagedArray"

Demo

The included example project shows a demo with a tweakable UITableViewController displaying a large number of rows using paging data.

Tests

The data structure is thoroughly tested by included XCUnit tests but no guarantees are given.

License

PagedArray is available under the MIT license. See the LICENSE file for more info.

pagedarray's People

Contributors

mralek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pagedarray's Issues

Array representation: [nil]

i can print the pagedArray object content but when i do something like this pagedArray[0], the result is always nil and after debugging i get this : Array representation: [nil]

Index out of bounds

I have recently encountered several crashes related to this function

/// Accesses and sets elements for a given flat index position.
    /// Currently, setter can only be used to replace non-optional values.
    public subscript (position: Index) -> T? {
        get {
            let pageIndex = page(for: position)
            
            if let page = elements[pageIndex] {
                return page[position%pageSize]
            } else {
                // Return nil for all pages that haven't been set yet
                return nil
            }
        }
        
        set(newValue) {
            guard let newValue = newValue else { return }
            
            let pageIndex = page(for: position)
            var elementPage = elements[pageIndex]
            elementPage?[position % pageSize] = newValue
            elements[pageIndex] = elementPage
        }
    }

specifically this line return page[position%pageSize] throws IndexOutOfBounds errors

Version used: 0.8

Real working example

Hi,
This looks like a great idea but I'm having some difficulty hocking the code to a real web service

Could please publish a working example.

Migrate to Swift 2.3 and Swift 3

In order to migrate and test our app to Swift 2.3/3.0 prior to the release of Xcode 8 and iOS 10, all of our dependencies need to be migrated first.

This can be solved by pointing our podfile to those respective Swift 2.3/3.0 branches, but this repo does not appear to have either of those branches.

This blog post contains helpful tips for migrating open source libraries.

Swift 2.0 Update?

Hello,

This looks great on paper. Unfortunately I couldn't try it because its not Swift 2.0 compatible.

Any chance we can see an update soon?

Thanks in advance and great work
Ace

Multiple API calls

I am trying to implement something similar with the Example.
I am setting the total count from the metadata of the first api call to get the first page.
however even though I am not scrolling yet, there are 5-6 api calls to get the first page.
Here is my code :


    fileprivate func loadDataIfNeededForRow(_ row: Int, withSearchText: String?) {
        var type: VehicleSearchType = .full
        if let _ = withSearchText {
            type = .filtered
        }
        let currentPage = pagedArray.page(for: row)
        if needsLoadDataForPage(currentPage, type: type) {
            loadDataForPage(currentPage, withSearchText: withSearchText)
        }
        
        let preloadIndex = row+PreloadMargin
        if preloadIndex < pagedArray.endIndex && shouldPreload {
            let preloadPage = pagedArray.page(for: preloadIndex)
            if preloadPage > currentPage && needsLoadDataForPage(preloadPage, type: type) {
                loadDataForPage(preloadPage, withSearchText: withSearchText)
            }
        }
    }
    
    private func needsLoadDataForPage(_ page: Int, type: VehicleSearchType) -> Bool {
        
        if type == .filtered {
            return filteredVehicleList.elements[page] == nil && dataLoadingOperations[page] == nil
        }
        return pagedArray.elements[page] == nil && dataLoadingOperations[page] == nil
    }

Does PagedArray play well with SwiftlyJSON?

Hello

Just wondering if this library plays well with JSON data Object. If so, how'd you go about linking them together?

if it?
pagedArray.setElements(JSONobject.arrayobject, pageIndex: 1)

Setting the PagedArray with an empty array hit the assert "Page index out of bounds"

func testSetEmptyElementsFirstPage() {
    var emptyArray: PagedArray<Int> = PagedArray(count: 0, pageSize: 10)
    emptyArray.setElements(Array(), page: 0)
    XCTAssertEqual(emptyArray.lastPage, 0)
}

func testSetEmptyElementsFirstPageWithStartPage() {
    var emptyArray: PagedArray<Int> = PagedArray(count: 0, pageSize: 10, startPage:1)
    emptyArray.setElements(Array(), page: 1)
    XCTAssertEqual(emptyArray.lastPage, 1)
}

Subscript crash when count changed

   func testPagedArraySubscriptAfterCountChanged() {
        var x = PagedArray<String>(count: 6, pageSize: 4, startPage: 1)
        x.set(["a", "b"], forPage: 2)
        x.count = 8
        let y = x[7] // crash
        XCTAssert(y == nil)
   }

It happens sometimes and I've found that best solution for me would be to make PagedArray bulletproof for that case. Could we have some simple solution like Here ? Or do you have some other suggestion ?

How to deal with unknown data count

Hi,

Could you provide some example how to deal with API data is not providing count of all data?
For now it looks that everything is based on known count.

Changes in the dataset

How can I handle the changes in the dataset ? I think this should work only if the data is not ordered or i'm i wrong ? If an ID is missing and added while you scroll you will have a shift in the rows

Connecting with the API responses

Hi, I am curious about the proper of connecting this library with the responses of my API. To be more clear, Our API sends back the data page by page which means I have to make a HTTP request for each page. I am looking for a library that could ease my job here, so do you think that I can use this repository? If yes, how? (the efficient way). Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.