How to store NSArray on Secondary storage?

喜欢而已 提交于 2019-12-11 06:24:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!