iOS - Incrementing ID number for creating filenames - ios

The application I'm working on creates pdf files and saves them in the device's documents directory. What I'm trying to do is create filenames with unique ID number, for example "invoice76.pdf".
How do I ensure each time the pdf file is created the number is incremented from the previous file name.
I tried using a global int but that obviously resets it each time the application is started.

Probably the simplest solution would be to store it in the NSUserDefaults. Alternatively, you could save the value in your own plist file.

Use this code which works betweeb app restarts:
- (void)storeIndex:(NSInteger)index{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//change value to new value
[defaults setInteger:index forKey:#"pdfIndex"];
//make save
[defaults synchronize];
}
- (NSInteger)lastIndex{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger value = [defaults integerForKey:#"pdsIndex"];
return value;
}
//stores new index and returns its value
- (NSInteger)incrementIndex{
NSInteger lastIndex = [self lastIndex];
lastIndex++;
[self storeIndex:lastIndex];
return lastIndex;
}

Pull an nsstring timestamp from nsdate, and if saving multiple files at the same time (and you don't want to use a massive timestamp) increment through n in a for loop. This will guarantee a unique ID. Then when loading, sort your array ascending and you have your list.

Related

UILabel text not being stored in NSUserDefault

I have a UILabel called 'labelA'. In this label is the letter 'A'.
When I am using NSUserDefault and start my app, the label is empty, but I don't know why?
Here is my ViewController.m file:
- (void)viewDidLoad {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
self->labelA.text = [defaults objectForKey:#"labelAtext"]; }
- (void)defaults {
NSString *textLabelA = labelA.text;
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:textLabelA forKey:#"labelAtext"];
[defaults synchronize];
}
Here is my NSString in the ViewController.h file
NSString *textLabelA =#"A";
When i load my app without NSUserDefault the labelA.text = A.
does anybody know what's my problem. Thanks a lot :-)
Your method defaults is not being called anywhere, so the text value is never stored in NSUserDefaults.
[self defaults]; // This needs to be called somewhere before you try and access NSUserDefaults.
You should also be accessing self using dot notation, not ->
self.labelA.text = [defaults objectForKey:#"labelAText"];
-> is for dereferencing a struct in C, for more information - What is "->" in Objective C?
When you use UserDefaults. You should first test if you get a value as if the value doesnt exist you need to set it or not.
NSString * myPreference = #"labelAtext";
- (void)viewDidLoad {
NSUserDefaults* userDefault = [NSUserDefaults standardUserDefaults];
id labelValue = [userDefault objectForKey:myPreference];
if (labelValue) // if preference exist
self.labelA.text = labelValue; // set ur label
else
[self storeDefaultValue]; // you store a default value
}
- (void)storeDefaultValue
{
NSString *myDefaultValue = nil;
if ([self.labelA.text isNotEqualToString:#""]) // if ur label not empty
myDefaultValue = self.labelA.text;
else
myDefaultValue = #"Not Available"; // or whatever defaults value you want
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myDefaultValue forKey:myPreference];
[defaults synchronize];
}
What do you really want to achieve as I don't really understand whats the point of storing a value in preference as soon as you load your app. Give more details on what is your goal.

Where to store Dictionary data in iOS

I am developing iPhone app,i have one doubt
I have an NSMutableDictionary which contains data in this format
dict at 0th index:
"ProductId":"77386",
"ProductImage":"http://static.abcd.com/images/product/large/design_gallery_slide_green - Copy (2).jpg",
"Productshortname":"Apple iPhone 5c 16GB",
"categorycode":null,
"categoryid":8,
"categoryimage":"",
"categoryshortname":"",
"favorite":"0",
"price":"31500",
"productnameinUrl":"apple-iphone-5c-16gb",
"storecount":"10"
dict at 1st index:
"ProductId":"11386",
"ProductImage":"http://static.abcd.com/images/product/large/design_gallery_slide_green - Copy (2).jpg",
"Productshortname":"Apple iPhone 5s 16GB",
"categorycode":null,
"categoryid":8,
"categoryimage":"",
"categoryshortname":"",
"favorite":"1",
"price":"31500",
"productnameinUrl":"apple-iphone-5s-16gb",
"storecount":"18"
dict at 2nd index:
"ProductId":"31386",
"ProductImage":"http://static.abcd.com/images/product/large/design_gallery_slide_green - Copy (2).jpg",
"Productshortname":"Apple iPhone 4s 16GB",
"categorycode":null,
"categoryid":8,
"categoryimage":"",
"categoryshortname":"",
"favorite":"1",
"price":"31500",
"productnameinUrl":"apple-iphone-4s-16gb",
"storecount":"38"
and so on...
What i want to do is, i want to store this dictionary indexes some where in my directory and i want to fetch it after some time or even after closing and opening the app after few times.
where should i store this kind of data ? is there any storage for strong this kind of data?
Please help and thanks in advance !!
You can store the data in NSUserdefaults and can access any time and anywhere as you want
yourdict;//Your NSDictionary Object That contains the data to store
[[NSUserDefaults standardUserDefaults] setObject:yourdict forKey:#"dict"];
[[NSUserDefaults standardUserDefaults] synchronize];
At the time of retrieval of data,
dict = [[NSUserDefaults standardUserDefaults] objectForKey:#"dict"];
You've already chosen an approved answer but I'll throw my thoughts in anyway.
This information looks like it could get large.
The user defaults isn't designed for large chunks of data. It's really meant for small bits of information, such as boolean preferences etc etc, not to be treated as an easy-to-use database.
Some problems with the user defaults:
The defaults file is read and parsed when you launch your app, regardless of whether you need your information from it at that time or not. This is because other parts of your app also use it for storing their bits of info too.
The entire defaults file needs to be parsed in order for you to retrieve anything, even if you just want a single entry.
You don't choose when the defaults file is parsed. You can't do any smart threading if it becomes huge (say you put 1000 products in there)
I'd recommend either writing the dictionary to it's own plist using NSDictionary's writeToFile: and reading using initWithContentsOfFile: (this still suffers from point #2 above)
OR
Using CoreData/sqlite to write the information to a real database.
NSDictionary methods: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDictionary/writeToFile:atomically:
An other option (And better in my experience) is to use - NSCoder, this option is great as you can use an Object with normal properties to access your data, which make your code more readable.
You can read about it here - NSCoding / NSKeyed​Archiver by NSHipster
An here is the reference - NSCoder docs
NSDictionary has a writeToFile: method which will do it for you.
NSDicationary writeToFile:Atomically:
use NSUserDefault and save your data like this in array
Here you can use this in anyway in your application for store value of NSUserDefaults.
// --- Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:#"TextToSave" forKey:#"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:#"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:#"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:#"floatKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
Here you can use this in anyway in your application for get value of NSUserDefaults.
// --- Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:#"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:#"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:#"floatKey"];
Thanks & Cheers ..
Looks like there can be more amount of data, so the best approach is to use core data to handle this scenario.
You can check few tutorials on how to use core data - Link1 , Link2
There are advantage of using core data over NSUserDefault and file system, as those load all the data at once and you might face some issue in performance.
You can also check following links which will illustrate you performance of different mechanism used to store data - PerformanceLinks1 PerformanceLinks2
try this
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"audio.caf",#"pictureAudioKey",
#"audio.m4a",#"englishAudioKey",
#"audio2.m4a",#"spanishAudioKey",
#"audio3.m4a",#"frenchAudioKey",
#"audio4.m4a",#"germanAudioKey",
#"audio5.m4a",#"italianAudioKey",
#"audio6.m4a",#"chineseAudioKey",
#"image.jpg",#"photoimagekey",
#"name.txt", #"identity",
#"imagename.txt",#"numberkey",nil];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *dictionaryPath = [documentsDirectory stringByAppendingPathComponent:[[self imageNameTextField]text]];
dictionaryPath =[dictionaryPath stringByAppendingFormat:#"dicitonary" ] ;
NSDictionary *savedDictionary = dictionary;
NSLog(#"The Save file is:%#", savedDictionary);
[savedDictionary writeToFile:dictionaryPath atomically:YES];

How to add to a saved NSUserDefault?

I am making a game in Xcode which in includes a scoring system in each level. Here I have some code that gets an NSString (passedValue1) by using a delegate.
Then i add the code to receive the value in my viewDidLoad and display my value in a UILabel
-(void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
// Do any additional setup after loading the view, typically from a nib
NSString *key=#"labelKey";
if(passedValue1){
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSObject * object = [prefs valueForKey:key];
if(object != nil){
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setValue:passedValue1 forKey:key];
[defults synchronize];
}
else{
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
NSInteger readScore=[[[NSUserDefaults standardUserDefaults] valueForKey:key] integerValue];
NSInteger newValue=readScore+[passedValue1 integerValue];
[defults setValue:[NSString stringWithFormat:#"%d",newValue] forKey:key];
[defults synchronize];
}
}
label.text = [[NSUserDefaults standardUserDefaults]objectForKey:key];
}
Once I have displayed the value I then save it into a label using a NSUserDefault. However, once I have replayed my game and have another score value I would like to add the new passedValue1 value to the currently saved value...
For example:
say I play my level and I get the score value of 10. The value is then saved and I replay my level. I would then like to take the saved value and add it to the value i just scored. So thats say the second value I have scored is 20. I would then like my code to add them together and give me a value of 30.
can anyone help because the code I'm using does not correctly do the function that I want to do which is add the previous and the currently passed value.
What is wrong with my code??
Thanks in advance.
You shouldn't use valueForKey: for this (it's not what you might think it is, see Key-Value Coding). Instead, you should use objectForKey: or in your case integerForKey:.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger value = [defaults integerForKey:key];
value += [passedValue1 integerValue];
[defaults setInteger:value forKey:key];
BOOL success = [defaults synchronize];
It seems that you got your if condition wrong, it should be
if (object == nil) { // <-- you have object != nil here !
// save new value
} else {
// read old value, add something, save new value
}

How can I add core data to a utility application

Ive made a simple ios utility application in xcode (version 4.4.1) but Ive realised that I need to store one integer in persistent memory. As far as I know using core data is the best way to achieve this.
Ive added the core data framework to my app but I dont know the code that I need to add for it to work.
Could someone please help
Thanks
If you just need to store/retrieve an integer, NSUserDefaults should be the way to go.
Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSInteger
[prefs setInteger:42 forKey:#"integerKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:#"integerKey"];
Reference:
http://www.icodeblog.com/2008/10/03/iphone-programming-tutorial-savingretrieving-data-using-nsuserdefaults/

iPhone first time application ran and config files

I'm developing an iPhone application and I want to know when it is the first time the application is executed. I want to check some extended permissions from facebook the first time.
How can I know that?
Another way to solved this problem is to store the extended permissions granted in some configuration file. I don't want to make visible this file through app settings icon.
How can I add some configuration files to store these permissions granted?
The std way would be to check if there is a value in NSUserDefaults and if that value doesn't exist (such as on first run) then create the value so on the rest of the starts you will know its not first run.
This is also a good candidate to use the NSUserDefaults and set key/value pares for each setting/permission you want.
Here's a quick tutorial on using NSUserDefaults.
Summary from that site for Saving:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:#"TextToSave" forKey:#"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:#"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:#"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:#"floatKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
Loading:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:#"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:#"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:#"floatKey"];
NSUserDefaults is perfect for saving app settings, and purchase history but if you are wanting to store much data then you should use another way.
Just write to a local file (xml or whatever).
Check, first, for the existence of the file. If not there this is the first run - otherwise just read the file.

Resources