Writing and reading custom object to file IOS

Nanoc picture Nanoc · Jun 5, 2013 · Viewed 7.4k times · Source

i have this object.

@interface SeccionItem : NSObject <NSCoding>
{
    NSString * title;
    NSString * texto;
    NSArray * images;
}

@property (nonatomic,strong) NSString * title;
@property (nonatomic,strong) NSString * texto;
@property (nonatomic,strong) NSArray * images;

@end

With this implementation

@implementation SeccionItem
@synthesize title,texto,images;


- (void) encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:title forKey:@"title"];
    [encoder encodeObject:texto forKey:@"texto"];
    [encoder encodeObject:images forKey:@"images"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    title = [decoder decodeObjectForKey:@"title"];
    texto = [decoder decodeObjectForKey:@"texto"];
    images = [decoder decodeObjectForKey:@"images"];
    return self;
}

@end

I want to save an array filled with this objects to a file on disk.

Im doing this:

to write

[NSKeyedArchiver archiveRootObject:arr toFile:file];

to read

NSArray *entries = [NSKeyedUnarchiver unarchiveObjectWithFile:name];
return entries;

But the readed array is always empty, i dont know why, i have some questions.

What format should i use for file path? on toFile:?

The NSArray on the object is filled with NSData objects, so i can encode them?

Im really lost on this.

Answer

Valent Richie picture Valent Richie · Jun 5, 2013

Take a look at the documentation of NSKeyedArchiver, especially the archiveWithRootObject:toFile: method.

The path is basically where the file should be stored including the file name. For example you can store your array in your app Documents folder with file name called Storage. The code snippet below is quite common:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docDir = [paths objectAtIndex: 0]; 
NSString* docFile = [docDir stringByAppendingPathComponent: @"Storage"];

The method NSSearchPathForDirectoriesInDomains is used instead of absolute path because Apple can be changing the Documents folder path as they want it.

You can use the docFile string above to be supplied to the toFile parameter of the archiveWithRootObject:toFile: method.