iphone - How to add value into array overtime user click on next button in xcode? -
when user click next button, generate random number , store number array. array storing last number only. should initialize array outside 'next' function? moreover, 'back button' read array last in number. please advise.
- (ibaction)next:(id)sender { // additional setup after loading view nib. //generate random number - result range of 0-10 int randomnumber = (arc4random() % 10); // add random number array [myarray addobject:[nsnumber numberwithint:randomnumber]]; // easy way in array nslog([myarray description]); nsstring *filename = [nsstring stringwithformat:@"file_no_%d", randomnumber +1]; //render complete file-path out of our filename, main-bundle , file- extension nsstring *filepath=[[nsbundle mainbundle] pathforresource:filename oftype:@"txt"]; //fetch text content file nsstring *mytext= [nsstring stringwithcontentsoffile:filepath encoding:nsutf8stringencoding error:nil]; //hand text on our textview textview.text=mytext; } - (ibaction)back:(id)sender { nsnumber *last_array_num = [myarray objectatindex:myarray.count - 1]; // read file name based on last number in array nsstring *filename = [nsstring stringwithformat:@"file_no_%d", last_array_num ]; }
you initializing array within next method adding it? if so, array needs initialized outside method, , once. keeps data intact, otherwise overwritten when initialize next time.
you adding array fine, doesn't need change @ all. reading number in method, need have following line of code:
edit: code use results want array. also, formal approach not start capital letters in code unless defines class (like nsstring). methods, this, should use - (ibaction)backbutton:(id)sender
instead. it's not big deal @ , code work fine, it's etiquette , keeps code bit less confusing in long run. have feeling might later, i'm letting know ahead of time. anyway, here code want
second edit: thinking, should make variable can read in code. in header file, add this
int arraycount;
in code, once myarray created, set arraycount
arraycount = [myarray count];
this should done if add or remove objects array.
then in action method, can call files
- (ibaction)back:(id)sender { nsstring *filepath = [nsstring stringwithformat:@"file_no_%d", [[myarray objectatindex:arraycount - 1] intvalue]]; // make sure aren't going beyond bounds of array; if (arraycount > 1) { // decrease count of arraycount; arraycount--; } }
using should allow move backwards in array 1 step each time click button. again, if isn't looking for, let me know , bottom of it
Comments
Post a Comment