2016-01-06 39 views
1

如果數組中的任何對象的「isSelected」屬性發生更改,我想更改數組中所有對象的「isSelected」屬性的值。我想在willSet事件中做到這一點。我有問題,如何獲取「isSelected」屬性的willSet事件中的數組(引用該對象)的引用。如果任何屬性值被修改,則更改數組中所有屬性的值swift(wiiSet)

class Survey: NSObject { 
var question = "N/A" 
var options = [SurveyOption]() 
init(Question question:String,options:[String]) { 
    self.question = question 
    self.options.appendContentsOf(SurveyOption.GetSurveyOption(options)) 
} 

class SurveyOption: NSObject { 
    var option = "N/A" 
    var isSelected = false 

    init(Option option:String) { 
     self.option = option 
    } 

    class func GetSurveyOption(options:[String]) -> [SurveyOption]{ 
     var surveyOptions = [SurveyOption]() 
     for option in options{ 
      surveyOptions.append(SurveyOption(Option: option)) 
     } 
     return surveyOptions 
    } 
} 


class func GetSurveyQuestions() -> [Survey]{ 
    let questions = [Survey]() 


    return questions 
} 

}

回答

0

使用NSNotificationCenter

1)在初始化

它看起來像,

init(Option option:String) { 
    self.option = option 
    NSNotificationCenter.defaultCenter().addObserver(
    self, 
    selector: "isSelectedValueChanged:", 
    name: NOTIFICATION_IS_SELECTED_VALUE_CHANGED, 
    object: nil) 

} 

2)在你的類添加選擇isSelectedValueChanged:類註冊通知NOTIFICATION_IS_SELECTED_VALUE_CHANGED

func isSelectedValueChanged(notification: NSNotification){  
    //do stuff 
    let changedValue = (notification.object as! NSNumber).boolValue 
} 

3)添加didSet{ }財產isSelected,併發布通知,如果財產改變,它會看起來像

var isSelected = false { 
     didSet{ 
NSNotificationCenter.defaultCenter().postNotificationName(NOTIFICATION_IS_SELECTED_VALUE_CHANGED, object: NSNumber(bool: isSelected)); 
     } 
    } 

每當財產isSelected值將被改變,通知將被解僱,並SurveyOption類的所有對象將收到通知,並且該方法isSelectedValueChanged:將與新認爲particuler對象的調用。