iOS development in order to store objects can use Nscoding, the object to be stored must experiment nscoding protocol
For example, if we want to store a student object, then the student class must follow the Nscoding protocol and then implement the two methods in Nscoding.
@interface Student : NSObject <NSCoding>
Then the. m file implements Encodewithcoder: (Save) and Initwithcoder: (read) method, which tells the program how the object should be stored, the properties to be stored, and how to read it!
/** * Called when an object is written to a file * In this method, it is clear which attributes need to be stored */-(void ) Encodewithcoder: (Nscoder *) encoder{[encoder encodeObject:self.no forkey:@ "no" ]; [Encoder encodeInt:self.age Forkey:@ "age" ]; [Encoder encodeDouble:self.height Forkey:@ "height" ];}
/** * 从文件中解析对象时会调用 * 在这个方法中说清楚哪些属性需要存储 */- (id)initWithCoder:(NSCoder *)decoder{ if (self = [super init]) { // 读取文件的内容 self.no = [decoder decodeObjectForKey:@"no"]; self.age = [decoder decodeIntForKey:@"age"]; self.height = [decoder decodeDoubleForKey:@"height"]; } return self;}
Read and Write methods in the controller.
- (ibaction) Save {//1. New Model ObjectStudent *stu = [[Student alloc] init]; Stu. No= @"42343254"; Stu. Age= -; Stu. Height=1.55;//2. Archiving Model Objects //2.1. Get full path to documents NSString*doc = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,YES) Lastobject];//2.2. Get the full path of the file NSString*path = [Doc stringbyappendingpathcomponent:@"Stu.data"];//2.3. Archive an Object[Nskeyedarchiver archiverootobject:stu Tofile:path];}
Anti-archive (read)
- (IBAction)read { // 1.获得Documents的全路径 NSStringYES) lastObject]; // 2.获得文件的全路径 NSString *path = [doc stringByAppendingPathComponent:@"stu.data"]; // 3.从文件中读取MJStudent对象 Student *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];}
iOS Dev-store uses nscoding archiving and anti-archiving