NSMutableArray *mutableArray = [NSMutableArray array];
Prostate *prostate = [Prostate new];
prostate.prostateCheckTimeString = self.prostateCheckTime.text;
prostate.prostateCubeString =self.prostateCube.text;
prostate.prostateAntigemString =self.prostateAntigem.text;
prostate.peeSpeedMaximumString =self.peeSpeedMaximum.text;
prostate.peeRemenderString =self.peeRemender.text;
[mutableArray addObject:prostate];
NSArray *tempArray = [[NSArray alloc]initWithArray:self.mutableArray];
[Global saveArrayToUserDefault:prostateArray saveValue:tempArray];
NSArray *array = [Global getArrayFromUserDefault:prostateArray];
//以下是我的全球对象
**+(void)saveArrayToUserDefault:(NSString *)userDefaultKey saveValue:(NSArray *)value**
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:value forKey:prostateArray];
[userDefaults synchronize];
}
**+(NSArray *)getArrayFromUserDefault:(NSString *)userDefaultKey**
{
NSArray *temp;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
temp = [userDefaults objectForKey:userDefaultKey];
return temp;
}
-----------------------------------说明-------- -------------------------------
我已经搜索了一段时间,我知道NSUserDefault只能存储NSArray,我试图将NSMutableArray转换为NSArray,但仍然有错误
-----------------------------------错误-------- -------------------------------------
属性列表格式无效:200(属性列表不能包含'CFType'类型的对象)尝试设置非属性列表对象( “”
答案 0 :(得分:4)
在您要保存的实体类中实现<NSCoding>
协议
-(void)writeArrayWithCustomObjToUserDefaults:(NSString *)keyName withArray:(NSMutableArray *)myArray {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray];
[defaults setObject:data forKey:keyName];
[defaults synchronize]; }
-(NSArray *)readArrayWithCustomObjFromUserDefaults:(NSString*)keyName {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:keyName];
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[defaults synchronize];
return myArray; }
答案 1 :(得分:1)
Prostate
是您的自定义对象,NSUserDefaults
不允许您保存它。
因此,在保存到NSUserDefaults之前必须Archive
,并在从NSUserDefaults
回读时取消归档。
因此,保存和读取用户默认数据的方法应如下所示:
-(void)writeArrayWithCustomObjToUserDefaults:(NSString *)keyName withArray:(NSMutableArray *)myArray {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray];
[defaults setObject:data forKey:keyName];
[defaults synchronize];
}
-(NSArray *)readArrayWithCustomObjFromUserDefaults:(NSString*)keyName {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:keyName];
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
return myArray;
}