【发布时间】:2016-10-23 00:33:17
【问题描述】:
学生.h
#import <Foundation/Foundation.h>
#import "Subject.h"
@interface Student : NSObject <NSCoding> {
NSString *studentID;
NSString *studentName;
NSMutableArray<Subject* > *subjects;
}
@property (copy) NSString *studentID;
@property (copy) NSString *studentName;
@property (copy) NSMutableArray<Subject* > *subjects;
-(Student *)initWithStudentID:(NSString *)ID andStudentName:(NSString *)name;
-(void)addSubject:(Subject *) subject;
@end
学生.m
#import "Student.h"
@implementation Student
@synthesize studentName;
@synthesize studentID;
@synthesize subjects;
-(Student *)initWithStudentID:(NSString *)ID andStudentName:(NSString *)name {
Student *student = [[Student alloc] init];
student.studentID = [NSString stringWithString:ID];
student.studentName = [NSString stringWithString:name];
return student;
}
-(void)addSubject:(Subject *)subject{
if(subjects==nil){
subjects=[[NSMutableArray alloc]init];
}
[subjects addObject:subject];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
[self setStudentID:[aDecoder decodeObjectForKey:@"studentID"]];
[self setStudentName:[aDecoder decodeObjectForKey:@"studentName"]];
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:subjects] forKey:@"subjects"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:studentID forKey:@"studentID"];
[aCoder encodeObject:studentName forKey:@"studentName"];
[aCoder encodeObject:subjects forKey:@"subjects"];
}
@end
主题.h
#import <Foundation/Foundation.h>
@interface Subject : NSObject
@property NSString *subjectID;
@property NSString *subjectName;
@end
主题.m
#import "Subject.h"
@implementation Subject
@end
Main.m
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *student1=[[Student alloc ]initWithStudentID:@"Nirmal" andStudentName:@"101"];
Subject *subject = [Subject alloc];
subject.subjectID=@"S01";
subject.subjectName=@"PHY";
[student1 addSubject:subject];
[NSKeyedArchiver archiveRootObject:student1 toFile:@"/Users/kuzhandaivel/Documents/nirmal.plist"];
Student *student2=[NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/kuzhandaivel/Documents/nirmal.plist"];
NSLog(@"%@",student2.studentID);
NSLog(@"%@",student2.studentName);
NSLog(@"%@",[student2.subjects description]);
}
return 0;
}
如何将类中存在的 NSMutablearray 保存到文件中? 上面的程序在以下行抛出以下错误:
[aCoder encodeObject:subjects forKey:@"subjects"];
encodeWithCoder 函数存在于 student.m 文件中。
【问题讨论】:
标签: ios objective-c