问题
I am new in iOS, i want to store the values in NSArray onto secondary storage so that i can access it later, The array is large response from web service, i want to parse and show it, It is not efficeint to parse the array and store in sqlite DB, I want alternate way to save that array, may be in text file, so that i cant retrieve data from text file and parse it by my parsing function. can we do that ?
please give me suggestions
Thanks in advance !
回答1:
to save the array to a text file you can use the method – writeToFile:atomically:
, for more information here is the documentation of the function.
回答2:
For retrieving "yourArray" from NSUserDefaults.. you can write in your controller:
-(id) initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self) {
yourArray = [[NSMutableArray alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (! [defaults objectForKey: [NSString stringWithFormat:@"sample"]])
{
//if nothing saved
//... do whatever you want
//Use this array if there is nothing saved
NSLog(@"no saved array");
NSArray *modelArray1 = @[@"New York", @"London", @"Paris"];
yourArray=[modelArray1 mutableCopy];
}
else{
NSLog(@"existing array");
NSData *myDecodedObject = [defaults objectForKey: [NSString stringWithFormat:@"sample"]];
yourArray =[NSKeyedUnarchiver unarchiveObjectWithData: myDecodedObject];
NSLog(@"decode array init=%u", yourArray.count);
}
}
return self;
}
for saving..
-(void)saving
{
NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:yourArray];
[userDefault setObject:myEncodedObject forKey:[NSString stringWithFormat:@"sample"]];
[userDefault synchronize];
}
回答3:
The best choice is [NSArray writeToFile:atomically:]
if array contains simple objects.
To get array back use NSArray's arrayWithContentsOfFile:
(Creates and returns an array containing the contents of the file specified by a given path.
+ (id)arrayWithContentsOfFile:(NSString *)aPath)
来源:https://stackoverflow.com/questions/14237782/how-to-store-nsarray-on-secondary-storage