Tuesday 15 April 2014

arrays - Save data even if the app re-opens - Swift Xcode 6 iOS -



arrays - Save data even if the app re-opens - Swift Xcode 6 iOS -

i'm working on app can randomize love couples. fun thing, okey!?!? :d problem, or maybe not problem thing can much improve if thing working. in origin need write in names. , thats takes time... should utilize core date? don't knows core info i'm not sure. love if god come me , wrote total code can remember array if app , phone shuts down. have done in java, simpel in java? great!

//thank, anton

for heavy, complex info structures want utilize core data, https://developer.apple.com/library/mac/documentation/cocoa/conceptual/coredata/articles/cdtechnologyoverview.html#//apple_ref/doc/uid/tp40009296-sw1

but seeing want store array, should nsuserdefaults. nsuserdefaults store given info long app not deleted. want create kind of custom datastorage class this.

@interface datastorage : nsobject <nscoding> @property (nonatomic, strong) nsmutablearray *arraytostore; + (instancetype)sharedinstance; - (void)save; @end

above .h file. can see, follows nscoding protocols. provides access methods allow encode data. utilize save method write info disk.

#import "datastorage.h" @implementation datastorage @synthesize arrayofpeople = _arraytostore; + (datastorage *)sharedinstance { static datastorage *state = nil; if ( !state ) { nsdata *data =[[nsuserdefaults standarduserdefaults] objectforkey:@"datastoragekey"]; if (data) { state = [nskeyedunarchiver unarchiveobjectwithdata:data]; } else { state = [[datastorage alloc] init]; } } homecoming state; } - (id)init{ if (self = [super init]) { if (!_arraytostore) { _arraytostore = [[nsmutablearray alloc] init]; } } homecoming self; } - (instancetype)initwithcoder:(nscoder *)decoder { self = [self init]; if (self) { if ([decoder decodeobjectforkey:@"datastoragearraytostore"]) { _arraytostore = [[decoder decodeobjectforkey:@"datastoragearraytostore"] mutablecopy]; } } homecoming self; } - (void)encodewithcoder:(nscoder *)encoder { [encoder encodeobject:_arraytostore forkey:@"datastoragearraytostore"]; } - (void)save { nsdata *appstatedata = [nskeyedarchiver archiveddatawithrootobject:self]; [[nsuserdefaults standarduserdefaults] setobject:appstatedata forkey:@"datastoragekey"]; [[nsuserdefaults standarduserdefaults] synchronize]; } @end

here .m file, pretty much evaluates see if there saved instance of class, , if not create one. [datastorage sharedinstance]...

when want store data, create class available said file, #import "datastorage.m , use

nsstring *testdata = [nsstring stringwithformat: @"test info string"]; [[datastorage sharedinstance].arraytostore addobject: testdata]; [datastorage sharedinstance] save];

ios arrays xcode swift save

No comments:

Post a Comment