Writing and reading custom object to file IOS

前端 未结 3 1929
盖世英雄少女心
盖世英雄少女心 2021-01-07 06:05

i have this object.

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

@property (nona         


        
3条回答
  •  不思量自难忘°
    2021-01-07 06:45

    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];
    
    }
    

提交回复
热议问题