iOS開發??保存自定義對象數組、字典到文件

iOS開發??保存自定義對象數組、字典到文件

2014-11-25 22:26html

在ios中,要保存普通的數組到文件能夠直接調用-wirteToFile:atomically:方法寫入,而且能夠經過NSArray的方法-initWithContentOfFile:來讀文件初始化數組。然而,當要保存的數組中存儲的數據對象是自定義對象時,就得經過對象歸檔的方法來實現了,具體來講ios


1、自定義對象實現歸檔協議,並實現方法- (id)initWithCoder:和方法- (void)encodeWithCoder:數組

@interface CourseModel : CYZBaseModel <NSCoding>


- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        self.courseName = [aDecoder decodeObjectForKey:@"courseName"];
        self.courseTeacher = [aDecoder decodeObjectForKey:@"courseTeacher"];
        self.courseTime = [aDecoder decodeObjectForKey:@"courseTime"];
        self.courseLocation = [aDecoder decodeObjectForKey:@"courseLocation"];
        self.shouldUseTip = [aDecoder decodeBoolForKey:@"shouldUseTip"];
        self.row = [aDecoder decodeIntegerForKey:@"row"];
        self.section = [aDecoder decodeIntegerForKey:@"section"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.courseName forKey:@"courseName"];
    [aCoder encodeObject:self.courseTeacher forKey:@"courseTeacher"];
    [aCoder encodeObject:self.courseTime forKey:@"courseTime"];
    [aCoder encodeObject:self.courseLocation forKey:@"courseLocation"];
    [aCoder encodeBool:self.shouldUseTip forKey:@"shouldUseTip"];
    [aCoder encodeInteger:self.row forKey:@"row"];
    [aCoder encodeInteger:self.section forKey:@"section"];
}


2、得到保存文件的路徑atom

- (NSString *)filePath
{
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"course.plist"];
}




3、調用NSKeyedArchived類的類方法:- (void)archiveRootObject:toFile:寫入文件 spa

    NSString *path = [self filePath];
    [NSKeyedArchiver archiveRootObject:self.allCourses toFile:path];



4、調用NSKeyedUnarchiver類的類方法:- (id)unarchiveObjectWithFile:讀文件.net

    NSString *path = [self filePath];
    self.allCourses = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if (self.allCourses == nil) {
        self.allCourses = [NSMutableArray array];
    }
相關文章
相關標籤/搜索