Search code examples
iosrubymotion

RubyMotion UITableView dataSource not returning properly


I’m new to RubyMotion. With this controller:

class LectureController < UIViewController


    def viewDidLoad
        super

        self.view.backgroundColor = UIColor.whiteColor

        @lectures ||= []

        Lecture.get() do |success, lectures|
            if success
                @lectures = lectures
                p "Received #{@lectures.length} lectures"
                @table.reloadData
            else
                App.alert("OOPS!")
            end
        end


        @table = UITableView.alloc.initWithFrame(self.view.bounds)
        self.view.addSubview @table
        @table.dataSource = self


        def tableView(tableView, numberOfRowsInSection: section)
            @lectures.count
        end

        def tableView(tableView, cellForRowAtIndexPath: indexPath)
            @reuseIdentifier ||= "CELL_IDENTIFIER"

            cell = tableView.dequeueReusableCellWithIdentifier(@reuseIdentifier) || begin
                UITableViewCell.alloc.initWithStyle(UITableViewCellStyleDefault, reuseIdentifier: @reuseIdentifier)
            end

            cell.textLabel.text = @lectures[indexPath.row].name

            cell
        end


    end

    def initWithNibName(name, bundle: bundle)
        super
        self.title = "Lectures"
        self
    end

end

I’m running into the following error message:

Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'UITableView dataSource must return a cell from
tableView:cellForRowAtIndexPath:'

As far as I can see, cellForRowAtIndexPath should be returning a cell. I can’t figure out why it won’t work.

Any help would be greatly appreciated.


Solution

  • Your two tableView methods are nested under your viewDidLoad method. They should be moved out to be part of the main LectureController class.

    In a typical Ruby class you may be able to get away with this (where calling the viewDidLoad method dynamically defines the other methods), but it won't work in RubyMotion due to the way the code is converted/compiled.