iOS開發——儲存自訂對象數組、字典到檔案

來源:互聯網
上載者:User

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




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.