cocoa touch - Loading data in NSUserDefaults -
i have done coding save highscore in nsuserdefaults, not sure how can load data nsuserdefaults , display in table. please help.
nsstring *name; name = nametextbox.text; nsdictionary *player = [nsdictionary dictionarywithobjectsandkeys: [nsstring stringwithformat:@"%@", name], @"name",[nsstring stringwithformat:@"%d", myscore], @"score",nil]; [highscore addobject:player]; nssortdescriptor *sort = [[nssortdescriptor alloc] initwithkey:@"score" ascending:no]; [highscore sortusingdescriptors:[nsarray arraywithobject:sort]]; [sort release]; [[nsuserdefaults standarduserdefaults] setobject:highscore forkey:@"highscore"];
you should able load way you'd expect (like accessing value in nsdictionary
):
nsarray *highscore = [[nsuserdefaults standarduserdefaults] objectforkey:@"highscore"];
update
to display data array in table view, you'll need create view controller , use array data source. easiest way subclassing uitableviewcontroller
. should started on implementation of controller:
// highscoreviewcontroller.h @interface highscoreviewcontroller : uitableviewcontroller { nsarray *highscores; } @property (nonatomic, retain) nsarray *highscores; @end
.
// highscoreviewcontroller.m #import highscoreviewcontroller.h static const nsinteger knamelabeltag = 1337; static const nsinteger kscorelabeltag = 5555; @implementation highscoreviewcontroller @synthesize highscores; - (void)viewdidload { [self sethighscores:[[nsuserdefaults standarduserdefaults] objectforkey:@"highscore"]]; } - (nsinteger)numberofsectionsintableview:(uitableview *)tableview { return 1; } - (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section { return [self.highscores count]; } - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *cellidentifier = @"playercell"; uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier]; if (cel == nil) { cell = [[[uitableviewcell alloc] initwithstyle:uitableviewcellstyledefault reuseidentifier:cellidentifier] autorelease]; // create uilabels name , score , add them cell uilabel *namelabel = [[uilabel new] autorelease]; [namelabel settag:knamelabeltag]; [cell.contentview addsubview:namelabel]; uilabel *scorelabel = [[uilabel new] autorelease]; [scorelabel settag:kscorelabeltag]; [cell.contentview addsubview:scorelabel]; // set other attributes common of cells here // need set frames of these labels (namelabel.frame = cgrectmake(...)) } nsdictionary *player = [self.highscores objectatindex:indexpath.row]; nsstring *name = [player objectforkey:@"name"]; nsstring *score = [player objectforkey:@"score"]; [(uilabel *)[cell.contentview viewwithtag:knamelabeltag] settext:name]; [(uilabel *)[cell.contentview viewwithtag:kscorelabeltag] settext:score]; return cell; } @end
a key thing remember uitableview
cells reused, need careful initialize/configure cell's subviews.
Comments
Post a Comment