Ellen
Ellen

Reputation: 13

Why is array empty after appending object to it

I am working in a TableViewController that I am trying to fill up with data from a plist.

I declared this at the top:

var studentsArray:Array<StudentData>?

And now I am doing the following in a function that loads my plist:

    var path = NSBundle.mainBundle().URLForResource("students", withExtension: "plist")
    let tmpArray = NSArray(contentsOfURL: path!)

    for studentDict in tmpArray!{
        let name = studentDict["name"]as! String
        let dateOfBirth = studentDict["dateOfBirth"] as! NSDate
        let regular = studentDict["regular"] as! Bool
        let photoFileName = studentDict["photoFileName"] as! String

        let data = StudentData(name : name, dateOfBirth: dateOfBirth, regular : regular, photoFileName: photoFileName)

        self.studentsArray?.append(data)
        println(studentsArray!.count)

    }

I tried logging the properties of the Object, they are all being filled in, but it goes wrong at the .append and somehow it just won't do that. The array's count remains 'Nil' when logged.

I'm kind of lost here! Any help is appreciated.

Upvotes: 1

Views: 1013

Answers (2)

Jorge
Jorge

Reputation: 1066

Try changing your array declaration to this and let me know if it works. Hope it helps:

var studentsArray:Array<StudentData>? = Array<StudentData>()

Upvotes: 0

Will M.
Will M.

Reputation: 1854

Doesn't look like you are initializing studentsArray anywhere. Make sure to do that. For the record, array.count should be 0 if the array is empty, not nil. If you are seeing nil that means the array is probably nil (aka you didnt initialize it).

Upvotes: 4

Related Questions