Bittoo Bittoo - 6 months ago 9
iOS Question

How to Save and Retrieve a Variable to/from Persistence in iOS?

Whenever I call my method generateTitleString I need to display a text to the user that says "Video X", where "X" is the number of the last video displayed to the user plus 1. If I use the below code, it is generating always the same number, which is 1.

- (NSString *) generateTitleString
{
NSString *title = [NSString stringWithFormat:@"Video %d", count+1];
return title;
}


How can I save and retrieve in/from persistence the value of the last video displayed so each time I display the "Video X" text it shows the increased count?

Thxs.

Answer

It looks like you are not increasing the variable count and that is why you get always "Video 1".

UPDATE: You can create a class where you can keep all your global variables (like "count"). In this example, I'm naming this class GlobalData. You also need to use User Defaults to permanently save the value of some of your variables.

Try the next.

GlobalData.h:

#import <Foundation/Foundation.h>

@interface GlobalData : NSObject

+ (NSInteger) getCount;

+ (void) setCount:(NSInteger)newCount;

@end

GlobalData.m:

#import "GlobalData.h"

#define COUNT_USER_DEFAULT_KEY @"COUNT_USER_DEFAULT_KEY"

@implementation GlobalData

/**
* It returns the number of the last video displayed.
*
* @param 
* @return the number of the last video displayed
*/
+ (NSInteger) getCount
{
    NSInteger count;
    NSString* recoveredValue;

    // init variables
    count = 0;
    recoveredValue = [[NSUserDefaults standardUserDefaults] valueForKey:COUNT_USER_DEFAULT_KEY];

    // If the recovered value is not NIL, we convert it to an integer.
    if (recoveredValue != nil)
        count = [recoveredValue integerValue];

    return count;
}

/**
* It sets the number of the last video displayed with the value of input "newCount".
*
* @param newCount    Number of the last video displayed.
* @return 
*/
+ (void) setCount:(NSInteger)newCount
{
    // Save user info in NSUserDefaults.
    [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%li", (long)newCount] forKey:COUNT_USER_DEFAULT_KEY];

    // Writes NSUserDefaults on disk.
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end

View Controller:

#import "GlobalData.h"

@implementation

- (void) viewDidLoad
{
     [super viewDidLoad];
}

- (NSString *) generateTitleString
{
    NSString *title;
    NSInteger count;

    // Getting count and increasing it.
    count = [GlobalData getCount];
    count = count + 1;        

    // Creating title by using 'count'.
    title = [NSString stringWithFormat:@"Video %d", count];

    // Updating 'count'
    [GlobalData setCount:count];

    return title;
}

@end