adding an item to at array in NSUserdefault - iphone

I am new to iOS development and could not find a way to solve this problem:
I have an app that has two views: one where the user enters some information (say a string), and another view where there is a tableview that includes all the strings that were ever entered (like a history view).
What I am trying to find is a good way to store the input string, then load it into the table view data source once the user switches to the history. I tried to use NSUserdefault but with not much success. Just getting messed up with the data structures, etc.
Here is what I am doing on the main view (where the user enters the input string):
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *arr1 = [[NSMutableArray alloc] init];
arr1 = [defaults arrayForKey:#"historyNames"];
[arr1 addObject:string];
[defaults setObject:arr1 forKey:#"historyNames"];
From some reason I get a warning where I read to arr1, and honestly, I doubt that should work anyway.
Can anyone suggest how I could modify this to work properly and achieve what I am looking for?
Thanks.

[defaults arrayForKey:#"historyNames"];
Will return nil if you never initialized and saved an array for that key in NSUSerDefaults.
If you initialize and array and set it once (look up how to initialize default values for NSUserDefaults), it will return a proper array.
Then you can just do
NSMutableArray *arr1 = [NSMutableArray arrayWithArray:[[defaults arrayForKey#"historyNames"]];
Depending on how many elements this array will have, you may be better off using Core Data. Using user defaults is not very efficient for many/large values, just for small settings and things like that.

When your application starts up, look in user defaults to see if you have an array object already from the last time you used it. If there isn't one, call alloc and init for arr1. (You don't want to call it if you're accessing it from defaults.)
NSMutableArray * arr1;
arr1 = (NSMutableArray *) [defaults objectForKey:#"historyNames"];
if (!arr1) {
arr1 = [[NSMutableArray alloc] initWithCapacity:20];
}
In your main view, just add the input string, and save the defaults.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject: arr1 forKey: #"historyNames"];
[prefs synchronize];

Related

storing data common to more than one view controllers

I know there are many ways for storing data like property list,archiving etc..but other than that is there any other way for storing very small amount of data,which is common to different view controllers(like a common class for storing all the data)?.
Try this
NSUserDefaults
when you want to save small amounts of data such as High Scores, Login Information, and program state.
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"];
[prefs synchronize];
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"];
We can do it by creating a singleton class and shared instance
Yes, you can define the required fields in form of an array. Now make sure that the form will provide you an identity and there is some validation through session etc. A a hook to your controller to sense the form submission every time with a particular flag (hidden). So the tablename and CRUD instruction will be provided to this function and every common CRUD functionality will be handled by this single function. By defining the required fields will let you ignore the extra ones like input buttons and many hidden fields.
use NSUserDefault to store values.
Yes you can declare in forms of NSMutableArray or NSMutableDictionary and access it any Viewcontrollers. You need to create a file as NSObject class and in
.h
+(NSMutableDictionary *)ImageCollection;
in .m file
+(NSMutableDictionary *)ImageCollection
{
static NSMutableDictionary *thestring =nil;
#synchronized([Global class]) // in a single threaded app you can omit the sync block
{
if (thestring ==nil) {
thestring=[[NSMutableDictionary alloc]init];
}
}
return thestring;
}
In any View Controllers include that NSObject class file
[[Global ImageCollection]setObject:#"Sample" forKey:#"Dictionary"]; //just example you can save string,image,array anything as you like
Hope this helps .. !!!
Use shared memory, to store and share common data between views.

NSUserDefaults problem

I have two views.In One view when i click on custom button it goes into second view,In that i have text view and that data must store in temperary memory so i used following code:
NSString *myString=txtvNote.text;
[txtvNote setText:#""];
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:myString forKey:#"note"];
[standardUserDefaults synchronize];
}
and when i go back on 1st view by clicking on the add button it will save into database for that i used following code:
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *val = nil;
if (standardUserDefaults)
val = [standardUserDefaults objectForKey:#"note"];
NSLog(#"Note::%#",val);
and then pass this value in insert query.
Now my problem is when i left that value blank,it takes the value which is inserted before.
sequence must be like this
//first set text to something
[txtvNote setText:#""];
//then use that text
NSString *myString=txtvNote.text;
myString is a pointer to the text in txtvNote. So if you set that text to #"" then myString will be empty as well. To preserve the value of txtvNote at the time of assignment use copy or reset the text after saving it:
NSString *myString=[[txtvNote.text copy] autorelease];
[txtvNote setText:#""];
....
That's the way NSUserDefaults works - every value is stored in your app's preferences, and like any other collection in Obj-C, it doesn't take nil values. Use instance of NSNull class or empty string. Or even better - use intermediate controller to store values and use key-value observing in your first view.

Pre-populating a NSUserDefaults array with Zero Value values

I need to pre-populate and save an array in NSUserDefaults so that downstream methods can read and write to ten values stored there. I've constructed this workable solution, but is there a better way of doing this?
Any insight is appreciated!
lq
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *myArray = [[NSMutableArray alloc] init];
// Set the array with ten Zero Value placeholders
for (NSUInteger i = 0; i < 10; ++i) {
[myArray addObject:[NSNumber numberWithInt:0]];
}
[userDefaults setObject:myArray forKey:#"someKeyName"];
[myArray release];
Later methods call this array like this:
- (void)doSomethingUseful {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *someUsefulArray = [[NSMutableArray alloc] initWithArray:[userDefaults objectForKey:#"someKeyName"]];
// read some values, write some values: int someInt = [someUsefulArray objectAtIndex:3]; // etc.
// store array values back to NSUserDefaults . . .
// IS THERE A WAY TO READ AND WRITE DIRECTLY TO INDEX 3 of the NSUserDefaults array instead???
[someUsefulArray release]
}
I've actually done the same thing in a shipping application. Sure, it doesn't feel elegant, but it does the job.
The only more elegant, and more convoluted, solution would be to use a data-driven approach:
Have a .plist file containing what you consider to be your default settings.
If the program detects that the user defaults is empty, it will load this default plist, and commit it to NSUserDefaults.
Using this method your code is not responsible for building the objects. However, if you are trying to accomplish a schema-upgrade, you're going to need to go back to the code.

iPhone code to create new NSUserDefaults objects?

I have NSUserDefaults storing a number of string variables for things like name, date of birth, address, etc. What I would like to know is how to write a code that will create a new object for each new user. For example, I have a spinning wheel that shows up immediately after the first time the user runs the app. What I want, is for that wheel to have one single option - "New User". Once that New User fills out a bunch of text fields that I am using NSUserDefaults to save, I want that user to be saved on that spinning wheel so that the next time they open up the app they have the option of returning to all of the variables that they previously put in, or creating a new user so they can input all new variables.
I know how to do everything except write the code to create new users automatically. Potentially, the program should allow for a limitless number of these user objects and then just use something arbitrary like their last name to input into the spinning wheel. I would assume that the code would need to be put somewhere in the following code used to save the NSUserDefaults:
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setObject:txtName.text forKey:#"name"];
---EDIT FOR CLARIFICATION ----
I am able to put multiple strings into this 'userData' object already by simply adding more lines like the 2nd line from above. What I want to know is how to add 'user2Data', 'user3Data', 'user4Data', 'usernData'..........to make a potentially limitless amount of user objects to store these variables?
You can add NSArray objects to NSUserDefaults.
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
NSMutableArray *users = [NSMutableArray mutableArrayWithArray:[userData objectForKey:#"users"];
[users addObject:txtName.text];
[userData setObject:[NSArray arrayWithArray:users] forKey:#"name"];
[userData setObject:txtName.text forKey:#"name"];
If you need more than a single string for user data, you can look at using an NSDictionary object.
All that said, if you're going to be storing a lot of data, you should look at maybe saving .plist files in your app's Library directory.
You could modify the following to meet your needs, to be put into your app delegate:
+ (void) initialize
{
if ([self class] == [MyAppDelegate class]) {
// initialize user defaults dictionary
BOOL isFirstTimeRun = YES;
...
NSMutableDictionary *resourceDict = [NSMutableDictionary dictionary];
[resourceDict setObject:[NSNumber numberWithBool:isFirstTimeRun] forKey:kIsFirstTimeRunKey];
...
[[NSUserDefaults standardUserDefaults] registerDefaults:resourceDict];
}
}
...
- (void) applicationDidFinishLaunching:(UIApplication *)application
{
if ([[[NSUserDefaults standardUserDefaults] objectForKey:kIsFirstTimeRunKey] boolValue]) {
// you could do first-time-run stuff here, such as initializing
// other data model elements...
}
...
}
...
- (void) applicationWillTerminate:(UIApplication *)application
{
// if we're quitting the app, it must have been run at least once
if ([[[NSUserDefaults standardUserDefaults] objectForKey:kIsFirstTimeRunKey] boolValue])
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:kIsFirstTimeRunKey];
...
}
What you probably want to do is create a property list for each user, and save the list of users in your NSUserDefaults. Once a user has been selected, you can then load the contents of the property list for that specific user and load/store all data in that particular property list. The basics of this approach is to use an NSDictionary* wherever you need to read from the property list and an NSMutableDictionary* whenever you need to both read and write to it. When you first construct the property list, you simply instantiate an NSMutableDictionary. When you want to save it or load it, you can use the NSPropertyListSerialization class in order to save or load the dictionary from/to a property list.

how can i store value in an NSArray using WritetoFile?

i wana store the index of seleted cell of table using NSArray, can u help me....
You can use user defaults or property list for this.
Example on user defaults. You have a controller class that has access to the index and will load it at startup and write it into plist whenever it's updated:
If you have some kind of controller class then you would put this code into + (void)initialize, it initialises the variable if it does not exists in plist:
+ (void)initialize
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults =
[NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:5]
forKey:#"MyFunnyIndex"];
[defaults registerDefaults:appDefaults];
}
In your -(void)awakeFromNib (I'm assuming you're using some kind of controller class) load your last stored value:
-(void)awakeFromNib
{
int index =
[[NSUserDefaults standardUserDefaults] integerForKey:#"MyFunnyIndex"];
[somethingThatNeedsIndex setIndex:index];
// ...
}
Somewhere where the index is updated (or where you want to write it to plist), let's call it - (void)updateInterface:
- (void)updateInterface
{
[[NSUserDefaults standardUserDefaults]
setObject:[NSNumber numberWithInteger:index]
forKey:#"MyFunnyIndex"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
I don't know if I understand the question correctly, but it sounds like you could use a property list to store this information. Property lists are very easy to use and quite efficient with small amounts of data.
Read the "Property List Programming Guide" for further explanation. There is even a tutorial in there.