user3511918
user3511918

Reputation:

How to save data from ViewController and Load it to TableViewController when app rerun?

So I have a class "WishListItem", a TableViewController and a ViewController. I'm having difficulties in saving chunk of data and retrieving it from TableViewController? How to do this effectively?

Here's my ViewController which has a prepareForSegue that stores data to my WishListItem class.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    NSDate *myDate = self.targetDatePicker.date;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMM d, YYYY"];
    NSString *prettyVersion = [dateFormat stringFromDate:myDate];

    if (sender != self.addWishListButton) return;
    if (self.wishTextField.text.length > 0) {
        self.wishItem = [[WishlistItem alloc] init];
        self.wishItem.wishlistItem  = self.wishTextField.text;
        self.wishItem.descWishItem = self.descTextField.text;
        self.wishItem.targetDate = prettyVersion;
    }
}

WishListItem.h :

@interface WishlistItem : NSObject

@property NSString *wishlistItem;
@property NSString *descWishItem;
@property NSString *targetDate;

@end

ViewController.h :

@interface JLSViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIBarButtonItem *addWishListButton;
@property (strong, nonatomic) IBOutlet UITextField *wishTextField;
@property (strong, nonatomic) IBOutlet UITextField *descTextField;
@property (strong, nonatomic) IBOutlet UIDatePicker *targetDatePicker;

@property WishlistItem *wishItem;

@end

From here. I want to save it every time I add a wishItem. How would I store MULTIPLE ENTRIES? and at the same time retrieve those entries in my TableViewController?

Please let me know if I need to provide more info. TIA.

Upvotes: 2

Views: 789

Answers (5)

Satheesh
Satheesh

Reputation: 11276

The easiest and the rude way of doing it is storing the data in NSUserDefaults

+(void)userDefaultsSetObject:(id)userObject forKey:(NSString *)userKey
{
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    [userDefaults setObject:userObject forKey:userKey];
    [userDefaults synchronize];
}

/**
 *  This method helps to get values from NSUserDefaults
 */

+(id)userDefaultsGetObjectForKey:(NSString *)userKey
{
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    return [userDefaults objectForKey:userKey];
}

Use the above two functions to save and retrieve data from NSUserDefaults. So coming to your problem here, add the wishlistitem objects to an array and set it in NSUserDefaults. Add this code to your tableviewcontroller class, and have a datasource array as a global variable.

 NSMutableArray *dataSourceArray;

In ViewDidLoad of the tableviewcontroller class add this,

NSMutableArray *wishlistItems;

if([self userDefaultsGetObjectForKey:@"WishListItems"]==nil)
{
  wishlistItems = [NSMutableArray array];
}
else
{
   wishlistItems = [self userDefaultsGetObjectForKey:@"WishListItems"];
}

dataSourceArray = [[NSMutableArray alloc] initWithArray:wishlistItems];

And in the tableViewDelegateMethod, try this:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [dataSourceArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    WishlistItem *wishListObject = [dataSourceArray objectAtIndex:indexPath.row];
    [cell.textLabel setText:wishListObject.wishlistItem];
    [cell.detailTextLabel setText:wishListObject.descWishItem];
    return cell;
}

So every time you add something do this,

- (NSMutableArray*)wishListAdded:(WishlistItem*)wishList
{
   NSMutableArray *wishlistItems;

   if([self userDefaultsGetObjectForKey:@"WishListItems"]==nil)
   {
     wishlistItems = [NSMutableArray array];
     [wishlistItems addObject: wishItem];
     [self userDefaultsSetObject:wishlistItems forKey:@"WishListItems"];
   }
   else
   {
     wishlistItems = [self userDefaultsGetObjectForKey:@"WishListItems"];
     [wishlistItems addObject:yourWishListObject];
     [self userDefaultsSetObject:wishlistItems forKey:@"WishListItems"];
    }
    return wishlistItems;
}  

Upvotes: 1

user3593011
user3593011

Reputation:

There are severals ways of saving data and retrieving them:

1. Saving data to NSUserDefaults (how Anonymous suggested): With NSUserDefaults you can save objects from the following class types: NSData, NSString, NSNumber, NSDate, NSArray, NSDictionary try to take a look at the documentation, UserDefaults is simple to understand and use. NSUserDefaults Doc

2. Saving data to Property List file (plist) It is kind of the same like UserDefaults (it can store the same data type) difference is you write your data in a document. But: Don't keep it in the Document folder unless it is appropriate for storage in iCloud, says Apple; Reference

3. Save data to a data base this will be another way to store your data...

At the end it all depends how complex will be the data you want to save, are we talking about strings and numbers or images NSUserNotification etc

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

NSDate *myDate = self.targetDatePicker.date;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMM d, YYYY"];
NSString *prettyVersion = [dateFormat stringFromDate:myDate];

if (sender != self.addWishListButton) return;
if (self.wishTextField.text.length > 0) 
{
       NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:self.wishTextField.text forKey:@"wishTextField"];
    [dict setObject:self.descTextField.text forKey:@"descTextField"];
    [dict setObject:prettyVersion forKey:@"prettyVersion"];
    NSMutableArray *array = (NSMutableArray*)[userDefaults objectForKey:@"myWishList"];
//check if array is not null i`m not sure if it will give you error if it is null
// if null NSMutableArray *array= [NSMutableArray alloc]init]; else             
    [array addObject:dict];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
    [userDefaults setObject:array forKey:@"myWishList"];

}
}

i think this should work for saving. For loading data in your:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath // methode 
//add this
 NSMutableArray *array = (NSMutableArray*)[userDefaults objectForKey:@"myWishList"];
// this will return all your wishlist items
  NSMutableDictionary *dict =  [array objectAtIndex:indexPath.row];
// this will give you the data you saved in the particular place 
 cell.textLabel.text = [dict objectForKey:@"wishTextField"];//this will be the name of the whishlist 

I think this should do

Upvotes: 0

Bug Hunter Zoro
Bug Hunter Zoro

Reputation: 1915

You can use mutablearrays for saving multiple objects of your wishlist class and then store that array in the userdefaults and retrieve it as per your needs.

Any changes made to the a particular object in the index of the array needs to be updated in the user default as well, else you will end up getting the same result set which you have stored in the first place.

Upvotes: 1

Gajendra Rawat
Gajendra Rawat

Reputation: 3663

To save your array state use this ie in view controller

NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];

use this where you want to retrieve the variable ie. intableViewController

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"preferenceName"];

Upvotes: 1

Suhit Patil
Suhit Patil

Reputation: 12023

I think you need to create the @property WishlistItem *wishItem; object in TableViewController .h file and save all the data while in segue method. So this is how your implementation will look like

in TableViewController.h

#import "WishlistItem.h"

@interface SomeTableViewController : UITableViewController

@property WishlistItem *wishItem

in JLSViewController.m

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    NSDate *myDate = self.targetDatePicker.date;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMM d, YYYY"];
    NSString *prettyVersion = [dateFormat stringFromDate:myDate];

    if (sender != self.addWishListButton) return;
    if (self.wishTextField.text.length > 0) {
       SomeTableViewController *tableViewController = [segue destinationViewController]; 
       tableViewController.wishItem = [[WishlistItem alloc] init];
       tableViewController.wishItem.wishlistItem  = self.wishTextField.text;
       tableViewController.wishItem.descWishItem = self.descTextField.text;
       tableViewController.wishItem.targetDate = prettyVersion;
    }
}

in TableViewController.m

you can populate the data in tableview using self.wishItem.wishlistItem etc.

if you want to save large data then consider using Core Data, also NSDateFormatter is expensive operation so you can refer this link for some improving that.

Upvotes: 0

Related Questions