您的当前位置:首页正文

存储方式

2024-12-14 来源:东饰资讯网

1、NSUserDefaults

是一个单例,支持的数据类型:NSNumber(NSInteger、float、double)、NSString、NSDate、NSArray,NSDictionary,BOOL。

� (1)、NSData*imageData = [defaults dataForKey:@"image"];

UIImage *Image = [UIImage imageWithData:imageData];//NSData转换为UIImage

(2)、NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"123",@"234", nil];

NSArray * array = [NSArray arrayWithArray:mutableArray];

NSUserDefaults *user = [NSUserDefaults standardUserDefaults];

[user setObject:array forKey:@"array"];

NSUserDefaults *user = [NSUserDefaults standardUserDefaults];

NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:[user objectForKey:@"array"]];

2、NSKeyedArchiver   存储自定义对象

-----student.h

#import<Foundation/Foundation.h>

@interface Student :NSObject<NSCoding>

@property(nonatomic,retain)NSString*name;

@property(nonatomic,retain)NSString*studentNumber;

@property(nonatomic,retain)NSString*sex;

@end

------student.m

#import "Student.h"

@implementation Student

-(void)encodeWithCoder:(NSCoder *)aCoder{

[aCoder encodeObject:self.name forKey:@"name"];

[aCoder encodeObject:self.studentNumber forKey:@"studentNumber"];

[aCoder encodeObject:self.sex forKey:@"sex"];

}

-(id)initWithCoder:(NSCoder *)aDecoder{

if (self=[super  init]) {

self.name=[aDecoder decodeObjectForKey:@"name"];

self.studentNumber=[aDecoder decodeObjectForKey:@"studentNumber"];

self.sex=[aDecoder decodeObjectForKey:@"sex"];

}

return self;

}

@end

#import "ViewController.h"

#import "Student.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

Student* student=[[Student alloc]init];

student.name=@"aaa";

student.studentNumber=@"123456";

student.sex=@"女";

NSMutableArray*dataArray=[NSMutableArray array];

NSData*data=[NSKeyedArchiver archivedDataWithRootObject:student];

[dataArray addObject:data];

NSArray* array=[NSArray arrayWithArray:dataArray];

NSUserDefaults* user=[NSUserDefaults standardUserDefaults];

[user setObject:array forKey:@"allstudent"];

//取数据

NSUserDefaults *userdefaults=[NSUserDefaults standardUserDefaults];

NSArray*arr=[userdefaults objectForKey:@"allstudent"];

NSData*data1=arr[0];

Student*stu=[NSKeyedUnarchiver unarchiveObjectWithData:data1];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

3、write

4、SQLite3

显示全文