Tuesday 15 January 2013

core data - How to point to objects that aren't yet instantiated -



core data - How to point to objects that aren't yet instantiated -

i preloading info on app's first launch core data, need point objects yet instantiated , can't figure out how this. saw similar question, though solution isn't applicable in situation.

say have 3 classes

class person { var nationofbirth: nation ... } class city { var mayor: person ... } class nation { var capitalcity: city ... }

if loading initial info set of nations, cities, people (or other order) no matter order load them in need set instances yet instantiated (though know be) , i'm struggling figure out how , appreciate help

one of fields must optional, because in illustration have cycle references. optional field in case must have week reference field clear memory correctly in end. code:

class person { var nationofbirth: nation init(nation: nation) { nationofbirth = nation } } class city { var mayor: person init(person: person) { mayor = person } } class nation { weak var capitalcity: city? } //initialization allow nation = nation() allow person = person(nation: nation) allow city = city(person: person) nation.capitalcity = city

in swift if declaring field in class without default initialisation must initialise in constructor(init). in case have 3 classes, each 1 field of class without default initialisation. need initialise in init method.

to initialise person need object of nation, initialise nation need object of city, initialise city need object of nation, , 1 time again need object of person, city, nation. you see infinity loop.

to solve problem need break loop. can setting field of 1 class optional (with ? in end of type). after don't need initialise field in initialiser, because can contain nil(nothing).

if don't need initialise in initialiser, can create fellow member of class optional field without object of class , set in end. in code can see, city field in nation set optional, can create fellow member of nation without initial city value(let nation = nation()).

after that, have fellow member of class nation, can create person initialiser takes nation object(let person = person(nation: nation)).

in same way have created fellow member of person can create fellow member of city(let city = city(person: person)).

in end have fellow member of city, can set nation object, created @ origin without city(nation.capitalcity = city).

about why need weak reference in case can read hear - https://developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/automaticreferencecounting.html#//apple_ref/doc/uid/tp40014097-ch20-xid_92

core-data swift instantiation

No comments:

Post a Comment