对象属性为尽管赋予他价值

时间:2016-03-25 14:36:02

标签: swift properties

我有以下课程:

class Event: NSObject {


    var eventID :String!
    var name: String!
init(name: String,eventID: String) {

        self.eventID = eventID
        self.name = name
    }

在我的视图中使用我的类的实例

     var selectedEvent: Event?

     func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

                let indexPath = tableView.indexPathForSelectedRow!

                print(listOfEvents[indexPath.row].eventID) // print my string
                selectedEvent.eventID = listOfEvents[indexPath.row].eventID
                print(selectedEvent.eventID) //print nil
     }

我做错了什么? 谢谢你的帮助

3 个答案:

答案 0 :(得分:0)

看看你是对象Event。它是nill

selectedEvent = Event(name: "Test", listOfEvents[indexPath.row].eventID)

答案 1 :(得分:0)

如果您将代码放入Playground,您将获得:

行的错误
selectedEvent.eventID = listOfEvents[indexPath.row].eventID

因为你的变量selectedEvent是nill,因为你已经声明了它但没有初始化它。为此,请替换

var selectedEvent: Event?

var selectedEvent = Event(name: "YourEventName", eventID: listOfEvents[indexPath.row].eventID)
奥列格提到它。

答案 2 :(得分:0)

如果listOfEventsEvent个对象的数组,您可以这样做:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    selectedEvent = listOfEvents[indexPath.row]
}