Swift低效的表视图模型?

时间:2015-03-29 12:23:00

标签: ios performance swift syntax model

我的语法可能效率不高,我在表格视图中对表示数据进行排序的方法也可能需要修改。

有关提高效率的任何提示都将非常感激。我的表格视图模型将是此类的一个实例,名为'会话详细信息'

class SessionDetails {

    // session -> registration -> person

    let session: Session
    private var _attendees: [Person]?
    var attendees: [Person] {
        get {
            if _attendees == nil {
            if let collection = self.session?.registrations {
                let sort = NSSortDescriptor(key: "created", ascending: true)
                if let registrations = collection.sortedArrayUsingDescriptors([sort]) as? [Registration] {
                    var collector = [Person]()
                    for registration in registrations {
                        if registration.person != nil {
                            collector.append(registration.person!)
                        }
                    }
                    _attendees = collector
                }
            }
            return _attendees!
        }
    }

    init(session: Session) {
        self.session = session
    }

    // rest of class truncated

编辑:会话,注册和人员是NSManagedObjects。会话具有NSSet注册。注册与Person一对一。换句话说,很多人都可以注册参加会议。

1 个答案:

答案 0 :(得分:0)

首先,如果您只有一个init()方法,则不需要将会话数据成员作为可选项。 init(session:Session)保证会话始终具有值。

如果session.registrations已修复且不会更改,那么您应该使与会者成为延迟加载属性。当访问与会者属性时,它将一次又一次地保存您进行排序。

class SessionDetails {

    let session: Session
    private var _attendees: [Person]?

    var attendees: [Person] {
        if _attendees == nil {
            //No optional binding i.e. 'if let' required as the initializer is not failing one.
            let sort = NSSortDescriptor(key: "created", ascending: true)

            //No optional binding i.e. 'if let' required as session is not optional. 
            //sortedArrayUsingDescriptors() method never returns nil.
            //Also we are sure returned array is of type [Registration] so no need to put as? operator.
            let registrations = session.registration.sortedArrayUsingDescriptors([sort]) as [Registration]

            var collector = [Person]()
            for registration in registrations {
                if let person = registration.person {
                    collector.append(person)
                }
            }
            _attendees = collector
        }
        return _attendees!
    }

    init(session: Session) {
        self.session = session
    }
}

如果让条件不需要,可以使它更精简并删除一些。