Populate TableViewController - ios

I am new to Swift and I dont have experience in coding in Objective C. The problem I am facing is that, when I populate data from the class object into table view cells all the cells show the same data (the last recently accessed array object). Could someone help me with this ?
Thanks.
class TableViewController: UITableViewController{
var urgentCenters:Array<UrgentCenterDetails> = []
override func viewDidLoad() {
super.viewDidLoad()
self.loadInfo()
println("Number of entries: \(self.urgentCenters.count)")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return 1;
}
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
//println("Number of rows \(urgentCenters.count)")
return self.urgentCenters.count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cellId = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? UITableViewCell
if nil==cell {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: cellId)
}
if let ip = indexPath{
cell!.textLabel.text = urgentCenters[indexPath.row].title
}
return cell
}
func loadInfo(){
// Append data to urgentCenters data
var center = UrgentCenterDetails()
var title:String
title = "Penn's Landing"
center.setCenterDetails(title)
urgentCenters.append(center)
title = "Liberty Bell"
center.setCenterDetails(title)
urgentCenters.append(center)
}
}

Your problem is that you are only creating a single UrgentCenterDetails object and adding it to the array multiple times. Because there is only a single object, when you change its properties you are affecting all elements of the array (because it is the same object in all elements).
You should have -
func loadInfo(){
// Append data to urgentCenters data
var title:String
title = "Penn's Landing"
center.setCenterDetails(title)
urgentCenters.append(center)
center = UrgentCenterDetails()
title = "Liberty Bell"
center.setCenterDetails(title)
urgentCenters.append(center)
}

Related

Cannot show Table View data in a simple Times Table App

I am trying to make a simple Times Table App (for numbers 1-9) in Swift) using a slider and a Table View. I am managing to make the slider work and an array to be created for each number that is selected with the slider and although the array is shown on the console. I cannot get the numbers to appear on the Table View. Can you please help me and tell me what am I missing?
Here is what I have written so far:
class ViewController: UIViewController, UITableViewDelegate {
#IBOutlet var sliderValue: UISlider!
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 9
}
#IBAction func sliderMoved(sender: UISlider) {
sender.setValue(Float(lroundf(sliderValue.value)), animated: true)
print(sliderValue)
var cellContent = [String]()
for var i = 1; i <= 10; i += 1 {
cellContent.append(String(i * Int(sliderValue.value)))
}
print(cellContent)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel?.text = cellContent[indexPath.row]
return cell
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I'm afraid there's quite a lot in the code you've supplied that doesn't make all that much sense. I've mentioned some of it in my comment above but you've also nested what looks like a tableViewDataSource-function into your sliderMoved function. The whole array thing looks rather flakey as well as the proposed cell-count does not actually consider the size of the array. I think you probably want something like this:
class ViewController: UIViewController, UITableViewDataSource {
#IBOutlet var valueSlider: UISlider!
#IBOutlet var tableView: UITableView!
private var cellContent = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
}
#IBAction func sliderMoved(sender: UISlider) {
sender.setValue(Float(lroundf(valueSlider.value)), animated: true)
tableView.reloadData()
}
// TableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 9
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") // Must exist with the same identifier in your storyboard
cell.textLabel?.text = valueStringForIndex(indexPath.row)
return cell
}
// Private functions
private func valueStringForIndex(index: Int) -> String {
return "\(index * Int(valueSlider.value))"
}
}
Have you tried creating cellContent array as a instance variable and the following code may work. Check it once.
var cellContent = [String]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 9
}
#IBAction func sliderMoved(sender: UISlider) {
sender.setValue(Float(lroundf(sliderValue.value)), animated: true)
print(sliderValue)
for var i = 1; i <= 10; i += 1 {
cellContent.append(String(i * Int(sliderValue.value)))
}
print(cellContent)
self.tableview.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel?.text = cellContent[indexPath.row]
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Although not directly an answer to your question ->
Depending on how you want the table displayed, a UICollectionView may be a great fit for this application. Very similar to UITableView to implement but with boxes and columns of data, may be simpler to format (and changing the slider could add some fun animation when the collection view updates).
The sample UIViewController below demonstrates using a UICollectionView. In the storyboard, I simply:
Added a UISlider, UICollectionView, and UILabel and created outlets in MultiplicationTableViewController
In the UICollectionView default cell I gave it the reuseIdentifier "numberCell", and added a label (to hold the product)
Made the MultiplicationTableViewController the dataSource and delegate for the UICollectionView
CODE:
import UIKit
class MultiplicationTableViewController: UIViewController {
#IBOutlet var timesTableCollectionView: UICollectionView!
#IBOutlet weak var numberSlider: UISlider!
#IBOutlet weak var label: UILabel!
var products = [Int]() //array to hold the computed value for each cell in the collectionView
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.viewRotated), name: UIDeviceOrientationDidChangeNotification, object: nil) //register for rotation notifications
products = createTableOfValues() //populate products with initial values
label.text = "\(Int(numberSlider.value)) x \(Int(numberSlider.value))"
}
#IBAction func sliderUpdated(sender: UISlider) {
sender.value = Float(Int(sender.value)) //make the slider stop only on whole numbers
label.text = "\(Int(sender.value)) x \(Int(sender.value))"
products = createTableOfValues() //create the new table values
timesTableCollectionView.reloadData() //tell the collectionView to read the new data and refresh itself
}
func createTableOfValues() -> [Int] {
var prod = [Int]() //temp array to hold the generated products
for row in 0...Int(numberSlider.value) { //iterate from row 0 (header) to
var columns = [Int]() //temp array to build column products
for column in 0...Int(numberSlider.value) {//iterate through each column, including column 0 (header)
if column == 0 {
columns.append(row)
} else if row == 0 {
columns.append(column)
} else {
columns.append(column * row)
}
}
prod.appendContentsOf(columns) //add the current row of products to the temp array
}
return prod
}
func viewRotated() {
timesTableCollectionView.reloadData() //called to force collectionView to recalc (basically to get new cell sizes
}
}
extension MultiplicationTableViewController: UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1 //required for UICollectionViewDataSource
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Int(numberSlider.value + 1) * Int(numberSlider.value + 1) //tells the UICollectionView how many cells to draw (the number on the slider, plus header rows)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("numberCell", forIndexPath: indexPath) //get an existing cell if it exists
if cell.frame.origin.y == 0.0 || cell.frame.origin.x == 0.0 { //if the cell is at the top or left of the collectionView
cell.backgroundColor = UIColor.yellowColor()
} else {
cell.backgroundColor = UIColor.clearColor() //If not, reset the color (required because cells are reused
}
cell.layer.borderColor = UIColor.blackColor().CGColor
cell.layer.borderWidth = 1.0
let numberItem = cell.viewWithTag(101) as? UILabel //get a reference to the label in the current cell
numberItem?.text = String(products[indexPath.row]) //get the value generated earlier for this particular cell
return cell
}
}
extension MultiplicationTableViewController: UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let columns = CGFloat(numberSlider.value + 1) //get the number of columns - slider value + 1 for header
let width = timesTableCollectionView.bounds.width / columns //divide the width of the collectionView by the number of columns
return CGSizeMake(width, width) //use width value to make the cell a square
}
}
Screenshot:

Reload UITableview after back

I have simple table on my View. Another view have array with some values. When I back, I want to reload table with new values, but dont work.
My class:
let textCellIdentifier = "cell"
var menu:[[String]] = [[]]
var buscaEmp:BuscadorEmpresa = BuscadorEmpresa()
#IBOutlet weak var tablaVista: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
recuperaEmpresas()
tablaVista.delegate = self
tablaVista.dataSource = self
}
func recuperaEmpresas(){
menu = buscaEmp.getEmpresas()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menu.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! CustomTableViewCell
let row = indexPath.row
cell.nombreEmp.text = menu[row][0]
return cell
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
recuperaEmpresas()
tablaVista.reloadData()
}
I use viewWillAppear to reload table before reopen the view.
in viewWillAppear, you have to call recuperaEmpresas() and after it, call tableView.reloadData().
With this, it will refill the menu datasource with fresh data from recuperaEmpresas() and reload the table view with the new datasource values.
Edit :
And be sure that recuperaEmpresas() refresh data with new data, if it's always the same, you won't see any changes...

Does not conform to UITableViewDataSource - Parse app

I'm using a UITableView in a ViewController connected to TodayViewController. I want to use data from my Parse database to load into the TableView.
Here is my TodayViewController class:
import UIKit
class TodayViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var InfoTableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
InfoTableView!.delegate = self
InfoTableView!.dataSource = self
loadParseData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadParseData() {
let query : PFQuery = PFQuery(className: "News")
query.orderByDescending("Headline")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("NewCell") as! PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NewCell")
}
//Extract values from the PFObject to display in the table cell
if let Headline = object?["Headline"] as? String {
cell?.textLabel?.text = Headline
}
if let Subtitle = object?["SubtitleText"] as? String {
cell?.detailTextLabel?.text = Subtitle
}
return cell
}
This error crops up:
How do I solve the problem? Is there any mistake in the overall structure? Do request for more information if required.
Yes you are not confirm to protocol UITableViewDataSource because you don't have a required method
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
So you need to inherit PFQueryTableViewController to use the methods you want
class TodayViewController: PFQueryTableViewController {
...
}
I think you have implemented all the delegate methods of tableview outside the main class, i mean there will be a open parenthesis { and the close parenthesis should be end of all the methods. try like this
import UIKit
class TodayViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var InfoTableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
InfoTableView!.delegate = self
InfoTableView!.dataSource = self
loadParseData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadParseData() {
let query : PFQuery = PFQuery(className: "News")
query.orderByDescending("Headline")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("NewCell") as! PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NewCell")
}
//Extract values from the PFObject to display in the table cell
if let Headline = object?["Headline"] as? String {
cell?.textLabel?.text = Headline
}
if let Subtitle = object?["SubtitleText"] as? String {
cell?.detailTextLabel?.text = Subtitle
}
return cell
}
}
Hope this will help.

Trying to display data on a UITableView from parse

I'm trying to display data from parse onto a UITableView but it's only displaying a blank UITableView (no data being shown)
I have a University class in parse, as well as a universityEnrolledName column name
here is the code
import UIKit
import Parse
import ParseUI
class viewUniversityList: PFQueryTableViewController {
#IBOutlet var uiTableView: UITableView!
override init(style: UITableViewStyle, className: String!){
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
self.parseClassName = "University"
self.textKey = "universityEnrolledName"
self.pullToRefreshEnabled = true
self.paginationEnabled = false
}
override func queryForTable() -> PFQuery {
var query = PFQuery(className: "University")
query.orderByAscending("universityEnrolledName")
return query;
}
override func viewDidLoad() {
super.viewDidLoad()
uiTableView.delegate = self
uiTableView.dataSource = self
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
if let universityEnrolledName = object?["universityEnrolledName"] as? String{
cell?.textLabel?.text = universityEnrolledName
}
if let classEnrolledName = object?["classEnrolledName"] as? String{
cell?.detailTextLabel?.text = classEnrolledName
}
return cell;
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
does anyone have any advice on displaying the universityEnrolledName data from the University class (from Parse)? Thanks!
Here,
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
This method is used to display number rows in a tableview. Since you are returning 0, which means you are telling to your table view that your table should have zero row's.
Similarly
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
By default table view have one section, if you are explicitly providing some value it will be overridden.
So in both case you should return some positive number greater than zero.
The below method should return UITableViewCell, but you wrote PFTableViewCell. So change it.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
if let universityEnrolledName = object?["universityEnrolledName"] as? String{
cell?.textLabel?.text = universityEnrolledName
}
if let classEnrolledName = object?["classEnrolledName"] as? String{
cell?.detailTextLabel?.text = classEnrolledName
}
return cell;
}
override func viewDidLoad() {
super.viewDidLoad()
//Conform to the TableView Delegate and DataSource protocols
uiTableView.delegate = self //set delegate
uiTableView.dataSource = self // set datasource
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0 //set count of section
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0 //set count of rows
}
Refere this:
how-to-make-a-simple-table-view-with-ios-8-and-swift
This might helps you :)
I don't write swift so forgive any syntax issues, but I expect you want something more like:
import UIKit
import Parse
import ParseUI
class viewUniversityList: PFQueryTableViewController {
#IBOutlet var uiTableView: UITableView!
override init(style: UITableViewStyle, className: String!){
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
self.parseClassName = "University"
self.textKey = "universityEnrolledName"
self.pullToRefreshEnabled = true
self.paginationEnabled = false
}
override func viewDidLoad() {
super.viewDidLoad()
uiTableView.delegate = self
uiTableView.dataSource = self
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func queryForTable() -> PFQuery {
var query = PFQuery(className: "University")
query.orderByAscending("universityEnrolledName")
return query;
}
override func textKey() -> NSString {
return "universityEnrolledName"
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = super.tableView(tableView, dequeueReusableCellWithIdentifier:indexPath, object:object) as! PFTableViewCell!
if let classEnrolledName = object?["classEnrolledName"] as? String{
cell?.detailTextLabel?.text = classEnrolledName
}
return cell;
}

Table view displays limited number of cells?

I want to display 128 cells in the table view. However, due to some reason the table view displays a maximum of five cells. I checked the number of rows returned by the code, it is greater than 5. So I am sure that part is correct. Also, I have written code for custom cell. Does this contribute to this behavior? If yes, what should I do ? If no, what am I doing wrong ?
/* Custom cell code */
class myCustomCell: UITableViewCell{
#IBOutlet var myTitle: UILabel!
#IBOutlet var mySubtitle: UILabel!
convenience required init(reuseIdentifier: String!){
self.init(style: UITableViewCellStyle.Value1, reuseIdentifier: reuseIdentifier )
}
}
/* code for table view */
import Foundation
import UIKit
import CoreLocation
class TableViewController: UITableViewController{
var rowNumber: String!
override func viewDidLoad() {
super.viewDidLoad()
//println("Count is : \(dataArray.count)")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return 1;
}
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
//println("Here Count is : \(dataArray.count)")
return dataArray.count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cellId = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? myCustomCell
//UITableViewCell
if nil==cell {
cell = myCustomCell(reuseIdentifier: cellId)
}
if let ip = indexPath{
var dict: NSDictionary! = dataArray.objectAtIndex(indexPath.row) as NSDictionary
cell!.myTitle.text = dict.objectForKey("name") as String
}
return cell
}
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath: NSIndexPath){
//println("Clicked \(didSelectRowAtIndexPath.row)")
}
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if(segue.identifier == "centerDetails"){
var svc = segue!.destinationViewController as CellClickController
var selectIndex = self.tableView.indexPathForCell(sender as UITableViewCell)
svc.cellIdx = selectIndex.row
}
}
}
Thanks!
The UITableView method dequeueReusableCellWithIdentifier is why only 5-ish cells are instantiated at one time. The UITableView only creates enough UITableViewCell objects are to fill the screen. When one scrolls off and is no longer in view, it is queued for reuse. If you are scrolling quickly, it may create more cells than the screen needs, but generally it will use just enough to cover the screen.
You can create a new UITableViewCell for each index path you display. However it will go out of scope when it scrolls offscreen unless you retain the object reference yourself. You can do this by adding it to an array that your class manages.

Resources