Container类使用包含字典的JsON数组进行初始化.这些词典用于初始化Entry类.但是,当访问条目或searchEntrIEs属性时,Entry对象的初始化会延迟发生.
@interface Container@property (Readonly,nonatomic) NSArray *entryDicts;@property (Readonly,nonatomic) NSArray* entrIEs;@property (Readonly,nonatomic) NSDictionary *searchEntrIEs;@end@implementation Container- (instancetype)initWithArray:(NSArray *)array{ self = [super init]; if (self) { _entryDicts = array; } return self;}@synthesize entrIEs = _entrIEs;- (NSArray *)entrIEs{ [self loadEntrIEsIfNeeded]; return _entrIEs;}@synthesize entrIEsByNumber = _entrIEsByNumber;- (NSDictionary *)entrIEsByNumber{ [self loadEntrIEsIfNeeded]; return _entrIEsByNumber;}- (voID)loadEntrIEsIfNeeded{ if (_entrIEs == nil) { // Load entrIEs NSMutableArray *entrIEs = [NSMutableArray arrayWithCapacity:[self.entrIEsDict count]]; NSMutableDictionary *entrIEsByNumber = [NSMutableDictionary dictionaryWithCapacity:[self.entrIEsDict count]]; [self.entrIEsDict enumerateKeysAndobjectsUsingBlock:^(Nsstring *number,NSDictionary *entryDict,BOol *stop) { Entry *entry = [[Entry alloc] initWithDictionary:entryDict container:self]; [entrIEs addobject:entry]; entrIEsByNumber[number] = entry; }]; _entrIEs = [entrIEs copy]; _entrIEsByNumber = [entrIEsByNumber copy]; // Delete dictionarIEs _entrIEsDict = nil; }}@end似乎这个问题已基本得到回答,但要回到原帖,这里(恕我直言)是一个相对简洁的Swift翻译.关键是你可以链接惰性属性.请注意,我同时使用了类函数和闭包 – 两者都很好.
import Swiftprintln("begin")class ClassWithLazyPropertIEs { lazy var entrIEs:[String] = ClassWithLazyPropertIEs.loadStuff() lazy var entrIEsByNumber:Dictionary<Int,String> = { var d = Dictionary<Int,String>() for i in 0..<self.entrIEs.count { d[i] = self.entrIEs[i] } return d }() private class func loadStuff() -> [String] { return ["Acai","Apples","Apricots","Avocado","Ackee","Bananas","BilberrIEs"] }}let c = ClassWithLazyPropertIEs()c.entrIEsByNumber // 0: "Acai",1: "Apples",2: "Apricots",3: "Avocado",4: "Ackee",5: "Bananas",6: "BilberrIEs"]println("end")总结
以上是内存溢出为你收集整理的Swift中的惰性属性初始化全部内容,希望文章能够帮你解决Swift中的惰性属性初始化所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)