Property delay Store Property objective-c practices
Sometimes we need to defer loading properties, which can be implemented in objective-c by overriding the getter method:
@property(nonatomic,Strong)Nsmutablearray*players;-(Nsmutablearray*) Players {if(!_players) {_players = [[NsmutablearrayALLOC] init]; }return_players;}New keywords for Swift
In SwiftlazyMark it, and note that it must bevarThe defined variable is not the only line, but also the attribute of class or struct. Note that global properties are not requiredlazyThe delay-loaded property of the tag. If you need to delay loading, you can put the deferred loading content in a closed package:
classPlayermanager {LazyvarPlayers: [String] = {varTemporaryplayers = [String] () Temporaryplayers.append ("Why")returnTemporaryplayers} ()}varp = Playermanager () p//{nil}P.playersp// {...}When to use delay loading
When should I load this function with delay? One of the most typical examples is when the initialization of a property must be done after the object is initialized.
For example, I have a person class and it has agreetingproperty to return to the greeting phrase. Like your name Wanghai, then it's"Hello, Wanghai"。 Its initialization depends on the current object'snameValue. You can then use the features of the deferred load:
classperson {varNameStringLazyvarGreeting:String= {[unowned self]inch return "Hello, \ (self.name)!"} () init (name:String) {self.name = name}}varp = person (name:"Why") p//{"Why", nil}P.greetingp//{"Why,{some" Hello, Why "}"}
There is a situation, that is, the computational volume is relatively large, you can use to lazy avoid unnecessary loading.
Calculated properties
The computed attribute corresponds to the stored property, but it isgetTo get the value through an optionalsetmethod to intercept the setting value. If notsetterThe property is read-only. A time class is used to demonstrate the use of computed properties:
class time{varSeconds:double =0Init (seconds:double) { Self. Seconds = seconds}varminutes:double {get {return(Seconds/ -)} set { Self. Seconds = (NewValue * -) } }}varTime = time (seconds: -) time.minutes//2Time.seconds//time.minutes= - //Time.seconds//
As you can see, the value of minutes is based on the seconds calculation.
Attribute observation
Sometimes when a property is changed
Or the top one?PersonClass example, the last time we used a delay load, this may be useddidSetImplementation, in the settingsnameUpdate aftergreetingValues of:
classperson {varNameString? {didset {self.greeting ="Hello, \ (self.name!)"} }varGreeting:String?}varp = person () p.greeting//NilP.name ="Why"P.greeting//"Hello, why" References
- Properties
- Lazy initialization with Swift
- Computed Properties in Swift
[Swift] DAY10: Properties