storing data common to more than one view controllers - iphone

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.

Related

adding an item to at array in NSUserdefault

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

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.

JSON and Core Data:Should I convert JSON into Core Data?

I'm new to Core Data and I need some help on my project.
I'm developing iPhone app that get JSON (Restaurants info) from server and shows the location on the map and table view, and stores favorite restaurants by pressing "add favorite" button.
For now, I'm just using NSDictionary and its functions to display data on the table and annotations and having favoriteRestaurant entity to store favorite restaurant data.
However, I would like to convert the NSDictionary object into Core Data object (Restaurant), and add "BOOL isFavorite" attribute to it and then delete favoriteRestaurant entity.
Make function that saves the restaurant object that passed and changes its "isFavorite" state, which is triggered by "add Favorite" button.
The favorite table shows only the restaurants that has been saved and isFavorite = YES.
I would like to know if this is right approach to accomplish what I want.
Thank you in advance!
Hi, thank you for fast responses. I forgot to say that I also want to implement MKAnnotation to that class so each annotation pin on the map belongs to unique restaurant object. If I want to do this, should I have another favorite class or Core Data entity, or just save it in the Restaurant table and make isFavorite = YES? Thank you, again!
If you're only concerned about saving the favorites then id go with plist serialization. I do the same thing in multiple apps. Normally I create a Helper class like below.
#import "Favorites.h"
#import "NSArray+Locations.h"
#implementation Favorites
+(void)addFavorite:(Location *)location{
NSMutableArray *remove = [NSMutableArray array];
[location.data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(#"%#,%#, %#",key,obj,[obj class]);
if([obj isKindOfClass:[NSNull class]])
[remove addObject:key];
}];
[location.data removeObjectsForKeys:remove];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary * favorites = [NSMutableDictionary dictionaryWithDictionary:[defaults objectForKey:FAVORITES]];
if(!favorites)
favorites = [NSMutableDictionary dictionaryWithCapacity:1];
[favorites setObject:location.data forKey:[location getID]];
[defaults setObject:favorites forKey:FAVORITES];
[defaults synchronize];
}
+(void)removeFavorite:(Location *)location{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary * favorites = [NSMutableDictionary dictionaryWithDictionary:[defaults objectForKey:FAVORITES]];
[favorites removeObjectForKey:[location getID]];
[defaults setObject:favorites forKey:FAVORITES];
[defaults synchronize];
}
+(NSArray *)getFavorites{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary * favorites = [defaults objectForKey:FAVORITES];
return [NSArray arrayWithLocations:[favorites allValues]];
}
+(BOOL)isFavorited:(Location *)location{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary * favorites = [defaults objectForKey:FAVORITES];
for(NSString *key in [favorites allKeys])
if([[location getID] isEqualToString:key])
return YES;
return NO;
}
#end
In this case the Location object is just a wrapper around a dictionary to make accessing the fields simpler.
If you want to save all of your data and not just favorites then I would go with core data otherwise a very large plist could give you memory headaches.
I like your approach. In my opinion Core Data is the way to go.
If you get lots of JSON records (say, dozens or hundreds of restaurants) with maybe even more data fields in the future, you could run into memory problems when using an array of NSDictionarys. Remember, a serialized plist can only be retrieved entirely, so if it gets large you will have to keep all the data in memory.
Also, you will very like have a much better performance from the start.
Your BOOL attribute (in Core Data that would be a NSNumber) should work fine for your purpose.

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.

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.