Friday, 2 August 2013

Storage File


           As u have used NSUserDefaults to store values of type whatever you want to choose from the List of Valid Object to set for a specified Key.
 Like if you want to set NSDictionary Object to NSUserDefaults then you use code like this  [[NSUserDefaults standardUserDefaults] setObject:dictionaryObject forKey:@"myDictionary"];
 Similarly Storage File will work for you.

 You Just need to use this file like

 [[SharedManager sharedManager] setObject:dictionaryObject forKey:@"myDictionary"];

 How it works--

 It has one static instance of storage file that it returns when you call [SharedManager sharedManager].
 As it is static instance, Any change to this file will reflect in all the class in which you are using it.And change from anywhere to this class will update it to be used in another class.

 It has its own plist file that keep your value persist when application closed.And return it to you whenever you call it again after launching application next time.

 Plus point is that you can also store CGRect and CGSize to this file.

SharedManager.h File

SharedManager.m File

---------------------

I have used this file as you can see below how to set data to it.


    SharedManager *sm=[SharedManager sharedManager];
   
    NSArray *myArray=[[NSArray alloc] initWithObjects:@"Rohan",@"Folks",@"Alien",@"Animals",@"Karizma",nil];
   
    NSDictionary *myDictionary=[[NSDictionary alloc] initWithObjectsAndKeys:@"Banana",@"Fruit",@"Zebra",@"Animal",@"Parrot",@"Birds",nil];
   
    NSString *myString=@"I am String";
   
    NSData *data=[myString dataUsingEncoding:NSUTF8StringEncoding];
   
    CGRect rect=CGRectMake(97, 443, 200, 450);
   
    CGSize size=CGSizeMake(340, 564);
   
    [sm setSize:size ForKey:@"mysize"];
    [sm setRect:rect ForKey:@"myrect"];
    [sm setData:data ForKey:@"mydata"];
    [sm setBool:YES ForKey:@"mybool"];
    [sm setObject:myString ForKey:@"myStr"];
    [sm setObject:myArray ForKey:@"myarray"];
    [sm setObject:myDictionary ForKey:@"mydict"];


And here is reference code to use this for getting info's you have set.

    SharedManager *sm=[SharedManager sharedManager];
   
    NSLog(@"my size string is %@",NSStringFromCGSize([sm sizeForKey:@"mysize"]));
    NSLog(@"my rectangle is %@",NSStringFromCGRect([sm rectForKey:@"myrect"]));
    NSLog(@"my data to string is %@", [[NSString alloc] initWithData:[sm dataForKey:@"mydata"] encoding:NSUTF8StringEncoding]);
    NSLog(@"my bool is %i",[sm boolForKey:@"mybool"]);
    NSLog(@"my array is %@",[sm ObjectForKey:@"myarray"]);
    NSLog(@"my dict is %@",[sm ObjectForKey:@"mydict"]);
    NSLog(@"my string is %@",[sm ObjectForKey:@"myStr"]);