Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save array of objects with properties to plist

I have a Mutable Array containing different objects such as strings, UIImage , etc. They are sorted like this:

Example:

BugData *bug1 = [[BugData alloc]initWithTitle:@"Spider" rank:@"123" thumbImage:[UIImage imageNamed:@"1.jpeg"]];
...
...
NSMutableArray *bugs = [NSMutableArray arrayWithObjects:bug1,bug2,bug3,bug4, nil];

So basically it's an array with objects with different properties.

I Tried to save a single string to a file with the next code and it's working fine but when I try to save the array with the objects, i get an empty plist file.

NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString * path = [docsDir stringByAppendingPathComponent:@"data.plist"];
NSLog(@"%@",bugs); //Making sure the array is full
[bugs writeToFile:path atomically:YES];

What am I doing wrong?

like image 209
Segev Avatar asked Dec 10 '12 12:12

Segev


2 Answers

When you write a string or any primitive data to plist it can be saved directly. But when you try to save an object, you need to use NSCoding.

You have to implement two methods encodeWithCoder: to write and initWithCoder: to read it back in your BugData Class.

EDIT:

Something like this : Change Float to Integer or String or Array as per your requirement and give a suitable key to them.

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:_title forKey:@"title"];
    [coder encodeFloat:_rating forKey:@"rating"];
    NSData *image = UIImagePNGRepresentation(_thumbImage);
    [coder encodeObject:(image) forKey:@"thumbImage"];
}


- (id)initWithCoder:(NSCoder *)coder {
    _title = [coder decodeObjectForKey:@"title"];
    _rating = [coder decodeFloatForKey:@"rating"];
    NSData *image = [coder decodeObjectForKey:@"thumbImage"];
    _thumbImage = [UIImage imageWithData:image];
    return self;
}

Even this will help you.

like image 70
Anoop Vaidya Avatar answered Nov 15 '22 07:11

Anoop Vaidya


Implement NSCoding in your BugData class as below

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeFloat:title forKey:@"title"];
    [coder encodeFloat:rank forKey:@"rank"];
    [coder encodeObject:UIImagePNGRepresentation(thumbImage) forKey:@"thumbImageData"];
}




- (id)initWithCoder:(NSCoder *)coder {
    title = [coder decodeFloatForKey:@"title"];
    rank = [coder decodeFloatForKey:@"rank"];
    NSData *imgData = [coder decodeObjectForKey:@"thumbImageData"];
    thumbImage = [UIImage imageWithData:imgData ];
    return self;
}
like image 36
Inder Kumar Rathore Avatar answered Nov 15 '22 08:11

Inder Kumar Rathore