Jozef Vrana
Jozef Vrana

Reputation: 309

Store data in tableview to NSUserDefaults

Tricks.h file

#import "Tricks.h"

@implementation Tricks

static NSMutableArray *trickList = nil;

+(NSMutableArray *)trickList
{
    if(!trickList){
        trickList = [[NSMutableArray alloc]init];

    }
    return trickList;
}

@end

Tricks.m file

@interface Tricks : NSObject

@property(strong, nonatomic) NSString *trickName;

Method for adding objects to array

-(IBAction)saveAction:(id)sender
{

    Tricks *trick = [[Tricks alloc]init];
    trick.trickName = self.trickLabel.text;
    [[Tricks trickList]insertObject:trick atIndex:0];
    [self.navigationController popViewControllerAnimated:YES];
}

In .h file of UITabelview class I am making a reference to tricks class, but I am sure there is error on this line.

@property (strong, nonatomic) Tricks *tricks;

In cellForRow method I am storing data

_trick = [[NSMutableDictionary alloc]initWithObjectsAndKeys:trick,nil];
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:_trick forKey:@"numberArray"];
[defaults synchronize];
NSLog(@"%@",_trick);

In .m class of UITableview in viewDidLoad I want to retrieve data

if([[NSUserDefaults standardUserDefaults] objectForKey:@"numberArray"] != nil) {
        _tricks = [[NSUserDefaults standardUserDefaults] objectForKey:@"numberArray"];

    }

Upvotes: 0

Views: 611

Answers (2)

zaph
zaph

Reputation: 112857

Add a method to Tricks that returns an object that NSUserDefaults can archive and a method that will restore from that object. Good candidate objects would be NSArray or NSDictionary.

Perhaps better yet, not knowing much about Tricks, add methods to Tricks to save and restore to NSUserDefaults with an object as above.

If Tricks has a substantial amount of information consider NSCoding and saving and restoring to a file in the app's Documents directory.

Upvotes: 0

iphonic
iphonic

Reputation: 12719

You are losing all the data because you are trying to save Tricks thats is NSObject and gets destroyed when your app gets killed, it works while the app is running and you create the NSUserDefaults better don't save it as Tricks objects, instead you can store your data as NSDictionary, or NSString which NSUserDefaults can store, and when you want to use it, you can create Trick object using your saved NSDictionary data.

Edit Only NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary can be stored using NSUserDefaults

Upvotes: 1

Related Questions