2

I've tried to lookup for answers on the Internet but I have found nothing that could help me.

Basically I have these restaurants that I want to save in a file and late read it. I save all the objects in an array for different uses later.

self.navigationItem.title = @"Restaurant Guide";
Restaurant *restaurant1 = [Restaurant new];
restaurant1.name=@"name1";
restaurant1.mark=@"1";
restaurant1.review=@"good";

Restaurant *restaurant2 = [Restaurant new];
restaurant2.name=@"name2";
restaurant2.mark=@"2";
restaurant2.review=@"bad";

restaurants = [NSArray arrayWithObjects:restaurant1, restaurant2, nil];
[restaurants writeToFile:(@"restaurantlist") atomically:NO];

But I figured if I do writetofile it won't work because it's not some strings, it's some objects. So how could I proceed?

Thank you

2 Answers2

0

You should implement <NSCoding> protocol in your Restaurant class and you should implement 2 methods in Restaurant.m file:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        _name = [aDecoder decodeObjectForKey:@"NAME"];
        _mark = [aDecoder decodeObjectForKey:@"MARK"];
        _review = [aDecoder decodeObjectForKey:@"REVIEW"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"NAME"];
    [aCoder encodeObject:self.mark forKey:@"MARK"];
    [aCoder encodeObject:self.review forKey:@"REVIEW"];
}

After that you can save your array to file:

- (void)saveToFile:(NSArray*)ar
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    //data.plist is name of your file, change it if require
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];

    [ar writeToFile:path atomically:YES];
}
Greg
  • 25,317
  • 6
  • 53
  • 62
  • `writeToFile:atomically:` only works with property list objects, you would have to replace the custom class objects with encoded `NSData` objects. It's easier just to archive the array and call `writeToFile:atomically:` on the archive. – Sebastian Dec 03 '13 at 11:16
-1

To save a custom object in a file your have to make that class as NSCoding complaint.

Here is a good tutorial for it http://www.raywenderlich.com/1914/nscoding-tutorial-for-ios-how-to-save-your-app-data

Basically you have to tell runtime that how your object should be converted into bytes so that it can be saved in a file. And by implementing NSCoding protocol you does that. By default your NSDate, NSString, NSNumber etc are NSCoding compliant so on saving these object we won't get any exception.

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184