0

I've had this problem for a very long time. I'm trying to populate a UITableView with NSMutableArray. But I'm not getting all the objects out side of the loop. The total count of objects is 167. But instead it returns 167 of the same object.

I declared the array outside of the loop like this:

class TableViewController: UITableViewController {

var sermon = SermonLink()
var sermons: NSMutableArray = []

override func viewDidLoad() {
    super.viewDidLoad()

    loadContent()
   }

The whole thing happens in a method:

func loadContent() {

var elements: NSArray = []


    let urlForHTML = NSURL(string:"http://ontherock.dk/?page_id=1141")
    var dataForHTML: NSData = NSData(contentsOfURL: urlForHTML!)!
    var htmlParser = TFHpple(HTMLData: dataForHTML)
    var htmlXPathString = "//td[@class='lyf_td_filename']/a"
    elements = htmlParser.searchWithXPathQuery(htmlXPathString) as NSArray

        var sermonArr:NSMutableArray = []
        for item in elements {
            var element: TFHppleElement = item as! TFHppleElement

            var firstChildItem: NSString = element.firstChild.content
            var dashSeperatedSermonArray = firstChildItem.componentsSeparatedByString("-") as! [String]


            sermon.subject = dashSeperatedSermonArray[4].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
            sermon.speaker = dashSeperatedSermonArray[3].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
            sermon.urlForAudioSermon = element.attributes["href"] as! String



            sermonArr.addObject(sermon)//Here inside the loop I get the expected data
        }
        sermons = sermonArr //sermons contains only the object at the last index, 167 times
        self.tableView.reloadData()
 }
3
  • Is SermonLink a class? Commented May 7, 2015 at 17:45
  • 1
    Amit89 is right, you are modfying the same sermon object over and over. You need to create a new sermon object inside the loop before the lines sermon.subject = ... Commented May 7, 2015 at 18:02
  • Yes SermonLink is a class. Okay. I'll try declaring the object inside as you suggest Commented May 7, 2015 at 18:13

1 Answer 1

1

The below could be the problem.

Since you initialised the var sermon = SermonLink() as a property of the class and you are updating same objects inside the for loop. Try to create this inside the for loop for each iteration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.