Data-populated controls are the core of almost every mobile application. In iOS, these controls are filled with data using the the delegate pattern and the data source concept. You can use this concept for controls like UITableView, UICollectionView and for our TKChart. However, you may not always be sure which control, for example UITableView or UICollectionView, is the best for your app when starting the development process. If at some point you decide to switch, you'll need to re-implement some code.
In this article I would like to introduce you to the TKDataSource component coming in Q1 2015 in Telerik UI for iOS. TKDataSource is a universal adapter that employs the common delegate pattern, but removes the burden of implementing different data protocols for the different controls.
It can consume various data types: simple arrays, arrays with business objects and dictionaries coming from various sources. Its data-shaping functionality allows you to sort, filter and group data items, and pass the data shaped view as a data source to data-driven components such as UITableView, UICollectionView, TKChart and others. Moreover, TKDataSource enables you to relate several controls to a single data source, enabling the synchronization of selected items.
The simplest way to use TKDataSource is to initialize it with an array. TKDataSource is an independent component and you can use it without connecting it to a UI control. The following code is in Swift, but the same convenient blocks API and methods will be available in Objective-C, and C# (for UI for Xamarin):
Here is the output from the console:
The only thing you need to do in order to show this data in UITableView is to set its dataSource property:
To achieve this result, we connect to a static JSON file stored at www.telerik.com, but you can connect to any web service that returns data in JSON format. Our JSON file provides weather information for a period of seven days:
The loadDataFromURL:dataFormat:rootItemKeyPath:completion: method is used to load the data in our data source:
In this code, we created a new instance of TKChart, initialized the dataSource property and set the valueKey property to humidityto display the humidity in a nice line chart.
Nikolay Diyanov Diyanov is the Product Manager of the Native Mobile UI division at Progress. Delivering outstanding solutions that make developers' lives easier is his passion and the biggest reward in his work. In his spare time, Nikolay enjoys travelling around the world, hiking, sun-bathing and kite-surfing.
Subscribe to be the first to get our expert-written articles and tutorials for developers!