godzilla
godzilla

Reputation: 3125

decoding my NSData

i am currently decoding my data send over the air using initWithDecoder. One of the things i have noticed is when it is called it can not see the variables within scope and therefore does not behave the way i intend it to, here is an example of what i have done:

first i encode all the data:

-(void) encodeWithCoder: (NSCoder *) encoder 
{
  for(BaseGroup *attackCard in myArray)
  {
    [encoder encodeObject: attackCard];
  }
}

within the same class i keep a note of the number of items i have:

self.numItems = [self.myArray count]; 

and within initWithCoder i expect to iterate and decode the encoded NSData as follows

-(id) initWithCoder: (NSCoder *) decoder
{

  for(int i =0; i < self.numItems; i++)
  {
    [self.myArray addObject:[decoder decodeObject]];   
  }

  return self;

}

trouble is that initWithCoder is out of scope from the variable numItems and therefore does not iterate at all. Is there a way around this?

Upvotes: 0

Views: 429

Answers (1)

sergio
sergio

Reputation: 69027

Why don't you encode/decode the full array? This would make things easier...

Also, don't forget to call [super init...]!

-(void) encodeWithCoder: (NSCoder *) encoder 
{
      [encoder encodeObject: myArray];
}


-(id) initWithCoder: (NSCoder *) decoder
{
   if ((self = [super init]))
       self.myArray = [decoder decodeObject];
   return self;
}

Upvotes: 1

Related Questions