what i'm trying accomplish build uitableview each cell has uiswitch on right, , when user opens app again switches stay in on/off positions @ corresponding index path.
i created nsarray of booleans , saved them nsuser defaults had road blocks while looping through them bool @ correct index set cells toggle switch either on or off.
would creating custom cell index path property better idea? have method save bool index path?
i'm relatively new programming know more advanced folks think quickest , easiest way go this.
many thanks!
here boolean controller save method public,
#import "boolcontroller.h" static nsstring *const boolarraykey = @"boolarraykey"; @implementation boolcontroller + (boolcontroller *)sharedinstance { static boolcontroller *sharedinstance = nil; static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ sharedinstance = [boolcontroller new]; }); return sharedinstance; } - (void)savebool:(bool)boolean { nsarray *arrayofbooleans = [[nsarray alloc]init]; arrayofbooleans = [arrayofbooleans arraybyaddingobject:[nsnumber numberwithbool:boolean]]; [[nsuserdefaults standarduserdefaults]setobject:arrayofbooleans forkey:boolarraykey]; [[nsuserdefaults standarduserdefaults]synchronize]; } - (nsarray *)booleans { return [[nsuserdefaults standarduserdefaults]objectforkey:boolarraykey]; } @end and here cell row @ index path method
- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:@"cell"]; uiswitch *toggleswitch = [[uiswitch alloc]initwithframe:cgrectmake(50, 10, 50, 30)]; [cell addsubview:toggleswitch]; if (toggleswitch.ison == yes) { [[boolcontroller sharedinstance]savebool:yes]; } if (toggleswitch.ison == no) { [[boolcontroller sharedinstance]savebool:no]; } return cell; }
as far understand problem i've come following conclusion:
- you should honor mvc pattern - don't store data in ui object (view).
- your savebool method creates new instance of array on every call , overwrites recent 1 when sync user defaults. use ivar in contoller outlives scope of function call instead...
you should take index path of row , store on/off state @ same index of array. array model in mvc setting...
so next time create tableview every row (index) gets right bool array (index) switches!!!
Comments
Post a Comment