Save the data in tableview to NSUserDefaults

综合技术 2018-06-17

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"];

    }

Thanks for advices

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.

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

Hello, buddy!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

玩转iOS开发:iOS中的Socket编程(二) 文章分享至我的个人技术博客: https://cainrun.github.io/14987134210457.html 接着讲 在之前的那篇文章...
WebKit学习—用WKWebView封装一个常用的WebViewController... 惯例先看效果图(后附demo地址) webVideo.gif 在iOS项目开发中,绝大多数功能都是我们原生开发的,但是像一些诸如用户协议说明,...
iOS Thanksgiving 2017: Tools & Libraries We... It’s that time of year where we gather with friends and family to ask who g...
PerformSegueWithIdentifier does not start I have a view controller with a button that launches the twitter login page via...
iOS网络协议—-HTTP/TCP/IP浅析 一.TCP/IP协议 话说两台电脑要通讯就必须遵守共同的规则,就好比两个人要沟通就必须使用共同的语言一样。一个只懂英语的人,和一个只懂中文的人由于没有...