你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS開發——保存自定義對象數組、字典到文件

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

編輯:IOS開發綜合

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


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

@interface CourseModel : CYZBaseModel 

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


二、獲得保存文件的路徑

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



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

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


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

    NSString *path = [self filePath];
    self.allCourses = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if (self.allCourses == nil) {
        self.allCourses = [NSMutableArray array];
    }




  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved