ScarletEnvy
ScarletEnvy

Reputation: 921

SWIFT TableView error

class MasterViewController: UITableViewController {

    let firstTable = [String]()
    let secondTable = [String]()

    var path = NSBundle.mainBundle().pathForResource("Chapters", ofType: "txt")
    var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)
    var content = (data)
    var line: [String] = content.componentsSeparatedByString("\n")

Error:

'MasterViewController.Type' does not have a member named 'path'

The next Question for @dip >> why does the table print an initial empty string? text is printed in the second cell instead of starting at 0

var path: String?
var data: String?
var TableView1 = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    self.path = NSBundle.mainBundle().pathForResource("textFile", ofType: "txt")
    self.data = String(contentsOfFile:path!, encoding: NSUTF8StringEncoding, error: nil)
    if var content = (data){
        //var line: [String] = content.componentsSeparatedByString("\n")
        var chp: [String] = content.componentsSeparatedByString("#")

        TableView1 += chp
    }...

Upvotes: 1

Views: 49

Answers (3)

dip
dip

Reputation: 3598

For computed Properties, you have to access via setter method, for example make optional global var like

var path:String?

and then lets say set value from inside viewDidload like

self.path = NSBundle.mainBundle().pathForResource("Chapters", ofType: "txt")

your error will go away! Hope it will help you!

Upvotes: 1

Shoaib
Shoaib

Reputation: 2294

Following change may also work;

private class var path:String {
    get {
        return NSBundle.mainBundle().pathForResource("Chapters", ofType: "txt")!
    }
}

var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)

Upvotes: 1

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

It is wrong way to initialise your data instance. Instead of that do it in your class method suppose you can do it in viewDidLoad method like this:

override func viewDidLoad() {
    super.viewDidLoad()
    var path = NSBundle.mainBundle().pathForResource("Chapters", ofType: "txt")
    var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)
    var content = (data)
    var line: [String] = content.componentsSeparatedByString("\n")
}

Upvotes: 0

Related Questions