Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

Use the following method to save data

-(NSString*)saveFilePath    {

        NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *pathString = [[pathArray objectAtIndex:0] stringByAppendingPathComponent:@"data"];
        //NSString *pathString = [[NSBundle mainBundle]pathForResource:@"Profile" ofType:@"plist"];
        return pathString;

    }

-(void)saveProfile  {
    SeccionItem *data = [[SeccionItem alloc]init]
    data. title = @"title";
    data. texto = @"fdgdf";
    data.images = [NSArray arrayWithObjects:@"dfds", nil];


    NSMutableData *pData = [[NSMutableData alloc]init];

    NSString *path = [self saveFilePath];

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:pData];
    [data encodeWithCoder:archiver];
    [archiver finishEncoding];
    [pData writeToFile:path atomically:YES];

}

Use the following method to load data

-(void)loadData {

    NSString* path = [self saveFilePath];
    //NSLog(path);
    NSMutableData *pData = [[NSMutableData alloc]initWithContentsOfFile:path];

    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:pData];
    data = [[SeccionItem alloc]initWithCoder:unArchiver];
    //NSLog(@"%@",data.firstName);
    [unArchiver finishDecoding];

}

For those who are seeking the solution in swift, I was able to write and read dictionary to file system as follows :

Write:

let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)  
do {
    try data.write(to: destinationPath)
} catch let error {
    print("\(error.localizedDescription)")
}

Read:

do
{
    let data = try Data.init(contentsOf: path)
    // path e.g. file:///private/var/ .... /Documents/folder/filename
    if let dict = NSKeyedUnarchiver.unarchiveObject(with: data){
        return dict                 
    }
}
catch let error
{
    print("\(error.localizedDescription)")
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top