When i call a method nothing happens - ios

I have a class where i store my methods:
.h file:
#import <Foundation/Foundation.h>
#interface SessionController : NSObject
-(void) addSession :(NSString *)userName
tipulContului:(NSString *)tipCont;
-(void) destroySession : (NSString *) userName;
-(NSString *) getSessionUsername;
-(NSString *) getSessionTipCont;
#end
.m file:
#import "SessionController.h"
#implementation SessionController
-(void) addSession : (NSString *)userName
tipulContului :(NSString *)tipCont
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:userName forKey:#"SessionUsername"];
[defaults setObject:tipCont forKey:#"SessionTipCont"];
NSLog(#"------------------------------------------------");
//NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
NSLog(#"%#", userName);
[defaults synchronize];
}
-(void) destroySession : (NSString *) userName
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:#"SessionUsername"];
[defaults removeObjectForKey:#"SessionTipCont"];
[defaults synchronize];
}
-(NSString *) getSessionUsername
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// verificam existenta utilizatorului
if([defaults stringForKey:#"SessionUsername"]!=nil && ![[defaults stringForKey:#"SessionUsername"] isEqual:#""]){
return [defaults stringForKey:#"SessionUsername"];
}
else
return nil;
}
-(NSString *) getSessionTipCont
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// verificam existenta Tipului de cont
if([defaults objectForKey:#"SessionTipCont"]!=nil && ![[defaults stringForKey:#"SessionTipCont"] isEqual:#""]){
return [defaults stringForKey:#"SessionTipCont"];
}
else
return nil;
}
#end
Than i call call the method from an external class like this
SessionController *sessionController;
[sessionController addSession:name tipulContului:type];
But the NSLog from the addSession method isn't called and the values that i send to the method aren't stored, it compiles and i don't have any warnings, what am i doing wrong?

You need to initialize your sessionController object
SessionController* sessionController = [[SessionController alloc] init];

The hyphen before the method name indicates the method is an "instance" method. You'll need to instantiate the object to utilize these. You're almost doing this. Try:
SessionController *sessionController = [[SessionController alloc] init];

Related

Objective C - Saving a variable inside NSUserDefaults

I have a class called "EntityType" that has a string "name" and I am using NSUserDefaults to save it so I tried this:
if (button.selected)
{
[button setSelected:YES];
[[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithBool:YES] forKey:#"buttonSelected"];
}
I want to access the variable from another class and save it inside NSUserDefaults
You have missed sync call.Apply this to save it.
if (button.selected)
{
[button setSelected:YES];
[[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithBool:YES] forKey:#"buttonSelected"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
to get it back later
NSNumber* savedValue = [[NSUserDefaults standardUserDefaults]
objectForKey:#"buttonSelected"];
This is if you want to store only the value.
If you want to store your custom object look at this link
How to store custom objects in NSUserDefaults
You can get NSNumber object like,
NSNumber *num = [[NSUserDefaults standardUserDefaults] objectForKey:#"buttonSelected"];
from anywhere in the app.
On your EntityType class, implement the following two methods for encoding and decoding (something relevant to your own object):
- (void)encodeWithCoder:(NSCoder *)encoder {
//Encode properties, other class variables, etc
[encoder encodeObject:self.name forKey:#"name"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
//decode properties, other class vars
self.name = [decoder decodeObjectForKey:#"name"];
}
return self;
}
Reading and writing from NSUserDefaults:
- (void)saveCustomObject:(MyObject *)object key:(NSString *)key {
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:encodedObject forKey:key];
[defaults synchronize];
}
- (MyObject *)loadCustomObjectWithKey:(NSString *)key {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [defaults objectForKey:key];
MyObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
Code borrowed from: save class in NSUserDefaults
**ViewController.h**
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
//here i took one userdefault property
#property(strong,nonatomic)NSUserDefaults *user;
#end
**ViewController.m**
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//after the property declaration take standard user defaults
_user = [NSUserDefaults standardUserDefaults];
//here i took Bool and key you can take any thing but took my_val
[_user setBool:YES forKey:#"my_val"];
}
// this is button action
- (IBAction)submit:(id)sender
{
//for bool i am checking the condition given above
if ([_user boolForKey:#"my_val"])
{
**enter code here**
NSLog(#"values is set to yes");
}
else
{
**enter code here**
NSLog(#"Value is set to No");
}
}

How to write similar codes efficiently in xcode?

Example 1:
- (NSString *)userToken
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
return [userDefaults objectForKey:#"userToken"];
}
- (void)setUserToken:(NSString *)userToken
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:userToken forKey:#"userToken"];
}
- (NSString *)userName
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
return [userDefaults objectForKey:#"userName"];
}
- (void)setUserName:(NSString *)userName
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:userName forKey:#"userName"];
[userDefaults synchronize];
}
These getter and setter are very similar. Is there a smart "macro" that can help me to simplify the codes? So I will be able to write few codes for each property like this:
XXXX(userToken)
XXXX(userName)
Example 2:
+ (MyManager *)sharedManager {
// singleton
...
}
- (void)updateName:(NSString *)name {
self.name = name;
}
+ (void)updateName:(NSString *)name {
return [[self sharedManager] updateName:name];
}
- (void)updateUid:(NSString *)uid {
self.uid = uid;
}
+ (void)updateUid:(NSString *)uid {
return [[self sharedManager] updateUid:uid];
}
I want a way to write them efficiently, too.
What can I do?

Obj C - NSUserDefaults won't give back values to calculate, after loading the view

I am stuck with little problem. I have basic calculating app.
Viewcontroller.m
#import "ViewController.h"
#interface ViewController () <UITextFieldDelegate, UIAlertViewDelegate>
#end
#implementation ViewController
-(void)textFieldDidEndEditing:(UITextField *)textField
{
self.currentSettings = _currentSettings;
[self calculateThePrice];
}
-(void)calculateThePrice
{
float wynik = self.currentSettings.kwh * self.currentSettings.price;
self.priceLabel.text = [NSString stringWithFormat:#"%.02f %#", wynik , self.currentSettings.currency];
}
SettingsVC.m
#import "SettingsVC.h"
#interface SettingsVC () <UITextFieldDelegate>
#end
#implementation SettingsVC
#pragma mark - UserDefaults Implementation
-(void)viewWillAppear:(BOOL)animated
{
[self createCurrencyArray];
NSUserDefaults *priceDef = [NSUserDefaults standardUserDefaults];
NSString *priceDefText = [priceDef stringForKey:#"priceCall"];
_priceTextField.text = priceDefText;
NSUserDefaults *currencyDef = [NSUserDefaults standardUserDefaults];
[_currencyPicker selectRow:[currencyDef integerForKey:#"currencyCall"]
inComponent:0 animated:NO];
[priceDef synchronize];
[currencyDef synchronize];
}
-(void)viewWillDisappear:(BOOL)animated
{
NSString *textOfPriceTexField = _priceTextField.text;
[[NSUserDefaults standardUserDefaults] setObject:textOfPriceTexField forKey:#"priceCall"];
}
Now, the problem is when I want program to automatically-calculate, it won't. To have any result, I have to switch to Second View, choose a value from picker and then when I will go back, I have my result.
But...
- When I change value on 1st screen, result won't change. When I change value on 2nd scree, result won't change. But when I change value on PickerView - TADAH - result updates!
When I go to second view, and go back to first, then go again to second and go back to first, my result changes to "0.00 (NULL)"...
Any ideas where I did wrong? I think it is about NSUserDefaults, I tried many options, nothing worked, nor changed anything.
You need to synchronize NSUserDefaults when you set new values. You are using synchronize when you retrieve values.
Here you don't need 2 pointers to defaults and don't need synchronize:
NSUserDefaults *priceDef = [NSUserDefaults standardUserDefaults];
NSString *priceDefText = [priceDef stringForKey:#"priceCall"];
_priceTextField.text = priceDefText;
[_currencyPicker selectRow:[priceDef integerForKey:#"currencyCall"] inComponent:0 animated:NO];
Here you need synchronizes:
-(void)viewWillDisappear:(BOOL)animated
{
NSString *textOfPriceTexField = _priceTextField.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:textOfPriceTexField forKey:#"priceCall"];
[defaults synchronize];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSInteger selectedRow = [_currencyPicker selectedRowInComponent:0];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:selectedRow forKey:#"currencyCall"];
[defaults synchronize];
self.currentSettings.currency = [self.currencyArray objectAtIndex:row];
self.currentSettings.price = [self.priceTextField.text floatValue];
//[self userDidFinishSetting];
}
Try this code
-(void)viewWillDisappear:(BOOL)animated
{
NSString *textOfPriceTexField = _priceTextField.text;
[[NSUserDefaults standardUserDefaults] setObject:textOfPriceTexField forKey:#"priceCall"];
}
-(void)viewWillAppear:(BOOL)animated
{
[self createCurrencyArray];
NSUserDefaults *priceDef = [NSUserDefaults standardUserDefaults];
NSString *priceDefText = [priceDef objectForKey:#"priceCall"];
}
instead of stringForKey you can call objectForKey same as for integerForKey also you can call objectForKey. Actually you are setting the object not string or integer.

Data to Userdefault encoder class for storing custom object

Can anyone give me any link or file, which could be used globally for a project to Store data to NSUserDefault.
Which contains method to save dictionary, array,string,integer all.
#import <Foundation/Foundation.h>
#import "BSUser.h"
#interface CLServerDataManager : NSObject
+(BOOL) saveServerDataToUserDefaults:(id)data;
+(NSDictionary*) getServerDataFromUserDefaults;
//For language Selection
+(void) setLanguage:(NSString*)LanguageName;
+(NSString*) getLanguage;
+(void) setUserPassword:(NSString*)password;
+(NSString*) getUserPassword;
+(void) setUserID:(NSString*)password;
+(NSString*) getUserID;
+(void) setUserUUID:(NSString*)uuid;
+(NSString*) getUserUUID;
+(void) setUserName:(NSString*)name;
+(NSString*) getUserName;
+(void) setimagedata:(float)data;
+(float) getimagedata;
+(void) setUserProfile:(BSUser*)user;
+(BSUser*) getUserProfile;
+ (void) setApplicationPurchaseStatus:(BOOL)purchaseStatus forUser:(NSString*)fbUserID;
+ (BOOL) getApplicationPurchaseStatusforUser:(NSString*)fbUserID;
+ (void) sethintAndTutorial:(BOOL)hintState;
+ (BOOL) gethintAndtutorial;
+ (void) setDeviceToken:(NSString*)deviceToken;
+ (NSString*) getDeviceToken;
//Methods for clear all data from user defaults
+ (void) resetServerDataManager;
#end
and .m file for this
#import "CLServerDataManager.h"
#import "ClConfig.h"
#implementation CLServerDataManager
+(BOOL) saveServerDataToUserDefaults:(id)data {
// if (!data) {
// return NO;
// }
// NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// [defaults setObject:data forKey:USER_ID];
// [defaults synchronize];
// return YES;
return NO;
}
+(NSDictionary*) getServerDataFromUserDefaults {
// NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// NSDictionary* rememberMe = [defaults objectForKey:USER_ID];
// if (rememberMe == nil) {
// return nil;
// }
// return rememberMe;
return nil;
}
//For the store user select language and again fetch
+(void) setLanguage:(NSString*)LanguageName {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:LanguageName forKey:#"Language"];
[defaults synchronize];
}
+(NSString*) getLanguage {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* Mylanguage = [defaults objectForKey:#"Language"];
if (Mylanguage == nil) {
return nil;
}
return Mylanguage;
}
//for store information cache for user's pics download
+(void) setimagedata:(float)data{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithFloat:data] forKey:#"cache"];
[defaults synchronize];
}
+(float)getimagedata{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
float data = [[defaults objectForKey:#"cache"] floatValue];
if (data == 0) {
return 0;
}
return data;
}
+(void) setUserPassword:(NSString*)password {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:password forKey:#"password"];
[defaults synchronize];
}
+(NSString*) getUserPassword {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* rememberMe = [defaults objectForKey:#"password"];
if (rememberMe == nil) {
return nil;
}
return rememberMe;
}
+(void) setUserID:(NSString*)password {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:password forKey:#"userID"];
[defaults synchronize];
}
+(NSString*) getUserID {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* rememberMe = [defaults objectForKey:#"userID"];
if (rememberMe == nil) {
return nil;
}
return rememberMe;
}
+(void) setUserUUID:(NSString*)uuid {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:uuid forKey:#"userUUID"];
[defaults synchronize];
}
+(NSString*) getUserUUID {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* rememberMe = [defaults objectForKey:#"userUUID"];
if (rememberMe == nil) {
return nil;
}
return rememberMe;
}
+(void) setUserName:(NSString*)name {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:name forKey:#"userName"];
[defaults synchronize];
}
+(NSString*) getUserName {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* name = [defaults objectForKey:#"userName"];
if (name == nil) {
return nil;
}
return name;
}
//store the current login user profile to user defaults
+(void) setUserProfile:(BSUser*)user {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:user] forKey:#"user_profile"];
[defaults synchronize];
}
+(BSUser*) getUserProfile {
BSUser* returnObject = nil;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [defaults objectForKey:#"user_profile"];
if (dataRepresentingSavedArray != nil)
{
returnObject = (BSUser*)[NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
}
return returnObject;
}
+ (void) setApplicationPurchaseStatus:(BOOL)purchaseStatus forUser:(NSString*)fbUserID {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithBool:purchaseStatus] forKey:fbUserID];
[defaults synchronize];
}
+ (BOOL) getApplicationPurchaseStatusforUser:(NSString*)fbUserID {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber* purchased = [defaults objectForKey:fbUserID];
if (purchased == nil) {
return NO;
}
return [purchased boolValue];
}
#pragma mark Set hint and tutotrial
+ (void) sethintAndTutorial:(BOOL)hintState{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithBool:hintState] forKey:#"hint"];
[defaults synchronize];
}
+ (BOOL) gethintAndtutorial{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber* hintstate = [defaults objectForKey:#"hint"];
if (hintstate == nil) {
return NO;
}
return [hintstate boolValue];
}
+ (void) setDeviceToken:(NSString*)deviceToken {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:deviceToken forKey:#"DeviceToken"];
[defaults synchronize];
}
+ (NSString*) getDeviceToken {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* name = [defaults objectForKey:#"DeviceToken"];
if (name == nil) {
return nil;
}
return name;
}
+ (void) resetServerDataManager {
[[self class] setLanguage:nil];
[[self class] setUserID:nil];
[[self class] setUserName:nil];
[[self class] setUserPassword:nil];
[[self class] setUserProfile:nil];
[[self class] setUserUUID:nil];
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString *domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"facebook"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
}
Try below link, You will get thing which you need..
NSUserDefaults

save and load uiswitch

I'm trying to make an appointment form on the iPad and I'm having trouble with the UISwitch, I need to save its state and the later load it on another page, I have done this for a text field and a date picker but for some reason it doesn't work for the UISwitch. I am very new to this so any help would be appreciated.
-(IBAction)savedata:(id)sender; {
NSString *savestring = _NameofResident.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestring forKey:#"savedstring"];
[defaults synchronize];
NSString *savestring1 = _NameofStudent.text;
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 setObject:savestring1 forKey:#"savedstring1"];
[defaults synchronize];
NSString *savestring2 = _AppointmentTime.date;
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
[defaults2 setObject:savestring2 forKey:#"savedstring2"];
[defaults synchronize];
NSString *savestring3 = _NextAppointmentTime.date;
NSUserDefaults *defaults3 = [NSUserDefaults standardUserDefaults];
[defaults3 setObject:savestring3 forKey:#"savedstring3"];
[defaults synchronize];
NSString *savestring4 = _Confirmed.text;
NSUserDefaults *defaults4 = [NSUserDefaults standardUserDefaults];
[defaults4 setObject:savestring4 forKey:#"savedstring4"];
[defaults synchronize];
}
- (IBAction)loaddata:(id)sender; {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedstring"];
[_NameofResident setText:loadstring];
NSString *loadstring1 = [defaults objectForKey:#"savedstring1"];
[_NameofStudent setText:loadstring1];
NSString *loadstring2 = [defaults objectForKey:#"savedstring2"];
[_AppointmentTime setDate:loadstring2];
NSString *loadstring3 = [defaults objectForKey:#"savedstring3"];
[_NextAppointmentTime setDate:loadstring3];
NSString *loadstring4 = [defaults objectForKey:#"savedstring4"];
[_Confirmed setText:loadstring4];
}
As you can see I can both load and save the state for the names and times but I don't really know how I can add in a UISwitch to do this.
thanks for your help.
To store the value of a UISwitch state, which is a BOOL, you can do 2 things :
store the BOOL in an NSNumber ([NSNumber numberWithBool:myBool]) and save it with defaults setObject: method. But then, when retrieving the BOOL, you will have to do [defaults objectForKey:#"myKey"].boolValue
store the BOOL itself with defaults setBool:forKey method. And retrieve it with defaults boolForKey method.
Moreover, I've seen you get the defaults many times and synchronize it many times. This is not necessary so I give you an example of what you could have done :
-(IBAction)savedata:(id)sender; {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *savestring = _NameofResident.text;
[defaults setObject:savestring forKey:#"savedstring"];
NSString *savestring1 = _NameofStudent.text;
[defaults setObject:savestring1 forKey:#"savedstring1"];
NSString *savestring2 = _AppointmentTime.date;
[defaults setObject:savestring2 forKey:#"savedstring2"];
NSString *savestring3 = _NextAppointmentTime.date;
[defaults setObject:savestring3 forKey:#"savedstring3"];
NSString *savestring4 = _Confirmed.text;
[defaults setObject:savestring4 forKey:#"savedstring4"];
BOOL savebool5 = _Switch.isOn;
[defaults setBool:savebool5 forKey:#"savedbool5"];
[defaults synchronize];
}
- (IBAction)loaddata:(id)sender; {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedstring"];
[_NameofResident setText:loadstring];
NSString *loadstring1 = [defaults objectForKey:#"savedstring1"];
[_NameofStudent setText:loadstring1];
NSString *loadstring2 = [defaults objectForKey:#"savedstring2"];
[_AppointmentTime setDate:loadstring2];
NSString *loadstring3 = [defaults objectForKey:#"savedstring3"];
[_NextAppointmentTime setDate:loadstring3];
NSString *loadstring4 = [defaults objectForKey:#"savedstring4"];
[_Confirmed setText:loadstring4];
BOOL loadBool5 = [defaults boolForKey:#"savedbool5"];
[_Switch setOn:loadBool5];
}
You can solve your problem the following way:
//
// ViewController.m
//
#import "ViewController.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UISwitch *mySwitch;
- (IBAction)switchChanged:(id)sender;
#end
#implementation ViewController
- (IBAction)switchChanged:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:self.mySwitch.on forKey:#"SwitchState"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.mySwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"SwitchState"];
}
#end
Happy programming !

Resources