对于保存对象数据到NSMutableArray 里 先要进行序列化 代码如下:
#import <Foundation/Foundation.h>
@interface ReviewUserInfo : NSObject<NSCoding> {
NSString *userName;
NSString *userReview;
NSString *userTime;
float userStarNum;
}
@property(nonatomic,copy)NSString *userName;
@property(nonatomic,copy)NSString *userReview;
@property(nonatomic,copy)NSString *userTime;
@property(nonatomic,assign)float userStarNum;
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
@end
#import "ReviewUserInfo.h"
@implementation ReviewUserInfo
@synthesize userName;
@synthesize userTime;
@synthesize userReview;
@synthesize userStarNum;
- (void) encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject:self.userName forKey:@"userName"];
[coder encodeObject:self.userReview forKey:@"userReview"];
[coder encodeObject:self.userTime forKey:@"userTime"];
[coder encodeFloat:self.userStarNum forKey:@"userStarNum"];
}
- (id) initWithCoder: (NSCoder *) coder
{
userName = [[coder decodeObjectForKey:@"userName"]copy];
userReview = [[coder decodeObjectForKey:@"userReview"]copy];
userTime = [[coder decodeObjectForKey:@"userTime"]copy];
userStarNum = [coder decodeFloatForKey:@"userStarNum"];
return self;
}
@end
------------------------
NSMutableArray*userNameArray = [[NSMutableArray alloc] init];
保存
ReviewUserInfo *userInfo =[[ReviewUserInfo alloc] init];
userInfo.userName =@"评论成功" ;
userInfo.userReview = @"评论成功" ;
userInfo.userTime = @"评论成功" ;
userInfo.userStarNum = 123;
[userNameArray addObject:userInfo];
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:userNameArray] forKey:@"UserReviewName"];
读取
NSData *dataRepresentingSavedArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"UserReviewName"];
if (dataRepresentingSavedArray != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
[userNameArray setArray:oldSavedArray];
}
用归档保存的对象,其子对象必须也支持归档包括自定义的对象。及实现initWithCoder和encodeWithCoder方