Cocoa - Store an NSString value - xcode

I want to store an NSString variable, that I receive from a JSON request, for future use. So when the user loads the app again, it loads that value (an NSString) that I stored.
What is the best way to store that kind of information?

NSUserDefaults is what you're looking for.
Save string:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:theStringToSave forKey:#"keyToLookupString"];
[prefs synchronize];
Retrieve string:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *theSavedString = [prefs stringForKey:#"keyToLookupString"];

Related

App terminates when using NSURL with parameters

In my app I sent a request to my PHP file to download some info. Whenever I use the code below it will terminate:
-(void)downloadItems
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:#"commentsId"];
NSLog(#"The comments id is : %#",myString);
// Download the json file
NSString *urlstring = [NSString stringWithFormat:#"http:/MyWebSite.com/checkphp.php?title=%#", myString];
NSURL *jsonFileUrl = [NSURL URLWithString:urlstring];
NSLog(#"The qasida id is: %#", jsonFileUrl);
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}
But if I remove myString from urlString like this:
NSURL *jsonFileUrl = [NSURL URLWithString:#"http:/myWebSite/checkphp.php?title=%#"];
the app will not terminate and it will retrieve data.
Can any one tell me what is wrong with my code?
Thanks

Can not update NSUserDefaults NSMutableDictionary Object

I'm trying to Update a Dictionary, saved in the UserDefaults.
However, it just doesn't want to update the Object at the given Index. I have no idea why. The Object with it's values stay the same.
Code:
- (void) saveUser
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *users = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"users"]];
BOOL userAlreadyAdded = FALSE;
NSUInteger count = 0;
for (NSMutableDictionary *user in users) {
if ([[user objectForKey:#"username"] isEqualToString:[defaults objectForKey:#"username"]]) {
NSLog(#"User found: %#", user);
[user setObject:sid forKey:#"sess"];
[user setObject:mid forKey:#"seca"];
[users replaceObjectAtIndex:count withObject:user];
userAlreadyAdded = TRUE;
}
count++;
}
if (!userAlreadyAdded) {
NSMutableDictionary *userToAdd = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
[defaults objectForKey:#"username"], #"username",
sid, #"sess",
mid, #"seca",
nil];
[users addObject:userToAdd];
}
NSLog(#"USERS TO SAVE: %#", users);
[defaults setObject:users forKey:#"users"];
[defaults synchronize];
}
Values returned from NSUserDefaults are immutable, even if you set a
mutable object as the value. For example, if you set a mutable string
as the value for "MyStringDefault", the string you later retrieve
using stringForKey: will be immutable.
try removing the object and adding it again.
For each user create a Mutable Dictionary from the one you have like you already did with 'users' (initWithArray).
NSMutableDictionary* mutableUser = [NSMutableDictionary dictionaryWithDictionary:user];
Also I'm not entirely sure you're safe to presume that the object at index of your count is the object you expect because the for in loop enumerates differently. I would use setObjectForKey, not replaceAtIndex.

How do I programmatically change system-wide desktop picture?

I'm using the following code to set desktop picture:
NSURL* newImage = [[NSURL alloc] initFileURLWithPath:#"/Users/name/Pictures/test.png"];
[[NSWorkspace sharedWorkspace] setDesktopImageURL:newImage forScreen:screen options:nil error:&nserror];
It works fine and the desktop picture changed as I required. But it does not change the system-wide desktop preferences (for example, change picture every 30 minutes). How can I change the system-wide desktop preferences?
Take a look at Preferences and Settings Programming Guide. This should help.
Edit:
Here is the sample code:
NSString* newImgPath = #"/Users/cody/Desktop/stuff/imgs/Black_mac.png";
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary* desktopDict = [NSMutableDictionary dictionaryWithDictionary:[defaults persistentDomainForName:#"com.apple.desktop"]];
NSMutableDictionary* bgDict = [desktopDict objectForKey:#"Background"];
NSMutableDictionary* spaces = [bgDict objectForKey:#"spaces"];
[spaces enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSMutableDictionary* obj, BOOL *stop) {
[obj enumerateKeysAndObjectsUsingBlock:^(id key, NSMutableDictionary* prefs, BOOL *stop) {
[prefs setObject:newImgPath forKey:#"ImageFilePath"];
[prefs setObject:newImgPath forKey:#"NewImageFilePath"];
[prefs setObject:#"Never" forKey:#"Change"];
}];
}];
//NSLog(#"%#", desktopDict);
[defaults setPersistentDomain:desktopDict forName:#"com.apple.desktop"];
if ([defaults synchronize] == NO)
NSLog(#"synchronize failed");
// Restart dock
system ("/usr/bin/killall Dock");

Save Global variable or a php like session

I'm working on my app but i need some help.
I need a 'php-like session' in Objective C (without using connection to the internet)
I've thought about global vars, but my app seems to reset them when reloading the view.
This is my current code
SecondViewController.h
#interface SecondViewController : UIViewController
{
NSString * string;
}
SecondViewController.m
#interface SecondViewController ()
#end
#implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
if (! [string isEqualToString:#"Hello"])
{
NSLog(#"Hello");
string = #"Hello";
}
else
{
NSLog(#"Bye");
}
}
#end
But everytime I reload SecondViewController the 'string' is reseted to its default value.
I'm looking for something that we use in php (a.e. $_SESSION['string'] = 'hello')
It could be helpful to you . It stores the values until unless delete the app from your device .
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];
**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"];

Xcode: Check if UIButton is hidden, using NSUserDefaults

How would I allow the app to save & load the current state of a button (i.e. if it is hidden, how would I save this, so that next time it will be hidden)? Also, I have it currently set so that when a button is pressed, all the other buttons become un-hidden. How can I set it so that certain ones don't become un-hidden if they have been set un-hidden in NSUserDefaults if you see what I mean?
Thanks
You can check with Apple's documentation on NSUserDefaults to get any additional information you need.
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
[defaults setObject:myBool boolForKey:#"hiddenButton"];
[defaults synchronize];
Then you can just pull it in the same way and set your hidden value.
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
myButton.hidden = [defaults boolForKey:#"hiddenButton"];
EDIT:
This would be one way to implement, but it really depends on what you want.
myViewController.h
BOOL myButtonState;
myViewController.m
-(void)viewDidLoad {
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
myButton.hidden = [defaults boolForKey:#"hiddenButton"];
}
-(IBAction)buttonPressed {
myButtonState = TRUE;
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
[defaults setObject:myButtonState boolForKey:#"hiddenButton"];
[defaults synchronize];
}

Resources