4

I have a mainObjectArray (NSMutableArray) which is populated with instances of a custom class. Each instance is itself an array, and objects in each array are NSDates, NSStrings, BOOL, and more arrays containing similar objects.

What I haven't been able to establish is whether it's possible to, inside the

- (void)encodeWithCoder:(NSCoder *)encoder 

method, to just say something like that:

[encoder encodeWithObject:mainObjectArray];

Or do have to encode every object in every instance separately? This would be a bit of a pain...

Your help would be very much appreciated.

Thomas Mary
  • 1,535
  • 1
  • 13
  • 24
Charl
  • 85
  • 1
  • 8
  • What do you mean by "each instance is itself an array"? Do you simply mean that your custom class instances **have** an array property? Or is it a subclass of `NSArray`? – yuji Feb 18 '12 at 17:59
  • Sorry for being inaccurate. My custom class is a subclass of NSObject, and has NSMutableArray, int, NSString, BOOL & NSDate as properties. – Charl Feb 19 '12 at 06:33
  • I've got a problem very similar to this. How would I go about saving an object with an NSArray of custom objects declared inside it? – Stuartsoft Jul 19 '12 at 13:39
  • @Charl: Hi Charl did you solve this issue. I am getting same problem. Can you suggest me. – Kittu Jun 16 '15 at 14:00

1 Answers1

6

Just implement the encoding and decoding methods in your custom class. That will do. Some sample,

- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:[NSNumber numberWithInt:pageNumber] forKey:@"pageNumber"];
    [encoder encodeObject:path forKey:@"path"];
    [encoder encodeObject:array forKey:@"array"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if(self = [super init]) 
    {
        self.pageNumber = [[aDecoder decodeObjectForKey:@"pageNumber"] intValue];
        self.path = [aDecoder decodeObjectForKey:@"path"];
        self.array = [aDecoder decodeObjectForKey:@"array"];
    }
}

You can see totally three data types being encoded and decoded - int, string, array.

Hope this helps.

cocoakomali
  • 1,346
  • 1
  • 8
  • 7
  • Hi cocoakomali! Thank you for your response. What I don't understand is, if it's possible to encode an array as you have done in the above example, why can I not just do the encoding with one line of code on my mainObjectArray? – Charl Feb 19 '12 at 06:32
  • Since your mainObjectArray is made from a custom class, you should implement the methods as I did. – cocoakomali Feb 20 '12 at 16:13
  • I've got a problem very similar to this. How would I go about saving an object with an NSArray of custom objects declared inside it? – Stuartsoft Jul 19 '12 at 13:38
  • what should `- (id)initWithCoder:(NSCoder *)aDecoder return – Nitin Apr 22 '14 at 06:21
  • return self for the initWithCoder – George Host Oct 05 '14 at 04:18