iPhone开发:综合NSValue和NSData

将前面的两篇文章综合起来,我们可以随心所欲地保存数据了

 

 

http://blog.csdn.net/iBright/archive/2010/06/08/5655857.aspx

http://blog.csdn.net/iBright/archive/2010/06/08/5656164.aspx

 

 

代码如下:

 

 

typedef struct _AA{

NSString *nameA;

}AA;

typedef struct _BB{

int k;

float m;

NSString *nameB;

AA aa;

}BB;

BB f[2] = {

{10,0.5f,@"bright",{@"a1"}},

{5,0.3f,@"mtf",{@"a2"}}

};

NSValue *value1 = [NSValue valueWithBytes:&f[0] objCType: @encode(BB)];

NSValue *value2 = [NSValue valueWithBytes:&f[1] objCType: @encode(BB)];

NSArray *array = [NSArray arrayWithObjects:value1,value2,nil];

NSLog(@"array == %@",array);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

if (!documentsDirectory) {

NSLog(@"Documents directory not found!");

}

NSString *appFile =[documentsDirectory stringByAppendingPathComponent:@"save"];

NSMutableData *data = [NSMutableData data];

[data appendBytes:&array length:sizeof(array)];

NSLog(@"data===%@",data);

[data writeToFile:appFile atomically:YES]; 

NSMutableData *readData = [NSMutableData dataWithContentsOfFile:appFile];

NSLog(@"readData==%@",readData);

NSArray *final;

[readData getBytes:&final range:NSMakeRange(0,sizeof(final))];

NSLog(@"final===%@",final);

BB c;

for (NSValue *aValue in final) {

NSLog(@"%@",aValue);

[aValue getValue:&c];

NSLog(@"%d",c.k);

NSLog(@"%f",c.m);

NSLog(@"%@",c.nameB);

NSLog(@"%@",c.aa.nameA);

}

 

posted @ 2010-06-08 17:09  javawebsoa  Views(203)  Comments(0Edit  收藏  举报