ios - Copy NSArray to member variable -
i have setter in class:
-(void)setnumbers:(nsarray *)anumbers{ nsarray *tarray = [[nsarray alloc]initwitharray:anumbers]; //throws bad access self.numbers = tarray; //also tried self.numbers = [tarray copy]; [tarray release]; }
if invoke setter this:
nsarray *numbers = [ticketmanager getrandomnumbersfor:@"lottonormal"]; [self.ticket setnumbers:numbers];
in 'getrandomnumbersfor:' method (the loop gets executed):
+(nsarray *)getrandomnumbersfor:(nsstring *)atickettype{ nslog(@"getting randomnumbers for: %@",atickettype); nsmutablearray *tresult; if([atickettype isequaltostring:@"lottonormal"]){ tresult = [nsmutablearray arraywithcapacity:6]; for(int = 0;i<6;i++){ int tnumber = arc4random() % 48; tnumber++; nslog(@"number: %i",tnumber); [tresult addobject:[nsnumber numberwithint:tnumber]]; } } return tresult; }
in viewcontroller
i´m getting bad access in marked line.
can can help?
by way, why have written setnumbers
setter method? given defined property, numbers
, setter method called setnumbers
synthesized you. worse, setnumbers
calls itself! construct
self.numbers = tarray;
is equivalent calling
[self setnumbers:tarray];
that results in infinite recursion.
as aside, i'd advise against writing own setnumbers
setter method unless there compelling reason so. default setter sorts of wonderful stuff (appropriate memory management, kvo, etc.), should think long , hard replacing own. let compiler synthesize accessor methods (setters , getters) you, if can.
if have write own accessor methods reason, @ least, make sure reference instance variables, not accessor methods.