is there an easier way to make something like this? - iphone

like the Q
i have this code
K1player1D.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"K1scoredLabel1"];
K1player1L.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"K1scorelLabel1"];
K1player1K.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"K1scorekLabel1"];
K1player1Q.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"K1scoreqLabel1"];
K1player1T.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"K1scoretLabel1"];
in viewDidLoad, for four players, so its 16 labels. is there any shorter way/code to do it ?

You could use NSMutableArray fill all the UILabel inside it and in a loop:
int i=1;
for(Player in ArrayOfUILabel){
Player.text = [[NSUserDefaults standardUserDefaults] objectForKey:(#"K1scoredLabel%d",i)];
i++;
}

EDIT
I would place them in an NSDictionary
NSDictionary * playerDict = [NSDictionary dictionaryWithObjectsAndKeys:
K1player1D,#"K1scoredLabel1",
K1player1L,#"K1scorelLabel1",
K1player1K,#"K1scorekLabel1",
K1player1Q,#"K1scoreqLabel1",
K1player1T,#"K1scoretLabel1",nil];
for(NSString * key in [playerDict allKeys]){
PlayerObject * player = [playerDict objectForKey:key];
player.text = [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

There is another way to do this using Joels's answer combined with KVC (Key value coding). I don't know if it's a particularly good approach, but I've included it for the sake of completeness:
NSDictionary * playerDict = [NSDictionary dictionaryWithObjectsAndKeys:
#"K1player1D",#"K1scoredLabel1",
#"K1player1L",#"K1scorelLabel1",
#"K1player1K",#"K1scorekLabel1",
#"K1player1Q",#"K1scoreqLabel1",
#"K1player1T",#"K1scoretLabel1",nil];
for(NSString * key in [playerDict allKeys]){
NSString *labelName = [playerDict objectForKey:key];
UILabel *label = [self valueForKey:labelName]; // grab the correct label using KVC
label.text = [[NSUserDefaults standardUserDefaults] objectForKey:key];
}
This could be made simpler if the label names matched the keys in the NSUserDefaults (then you could just use an array of names instead of a dictionary).

Related

How to remove a null value directly from NSDictionary

I´m a beginer and have lately got a great deal of trouble with this issue.
I want to pass a NSDictnonary Data to a server from my app and in some cases if the user hasen´t chosen any option I want to remove nil objects.
I have looked into this thread that seems be the right method but I haven't succeed to implement in my code.
How to remove a null value from NSDictionary
My guess would be to implement the code to Null directly in my NSDictonary
Here´s my Dictionary code
-(NSDictionary*)parametersForCreateActivities
{
NSString *token = [[A0SimpleKeychain keychain] stringForKey:tokenConstant];
NSString *userId = [[A0SimpleKeychain keychain] stringForKey:child_id];
NSString *userCreate = [[NSUserDefaults standardUserDefaults] objectForKey:#"CreateTitle"];
NSString *createDescription = [[NSUserDefaults standardUserDefaults] objectForKey:#"DescriptionText"];
NSString *createTimestart = [[NSUserDefaults standardUserDefaults] objectForKey:#"TimeStartString"];
NSString *createTimestop = [[NSUserDefaults standardUserDefaults] objectForKey:#"TimeStopString"];
NSString *createImage = [[NSUserDefaults standardUserDefaults] objectForKey:#"DefaultcreateImageID"];
NSDictionary *parameters;
if (userId && token) {
parameters = #{child_id: userId, tokenConstant:token, activity_name :userCreate, create_Description :createDescription, create_Timestart :createTimestart, create_Timestop :createTimestop, create_Image :createImage};
}
return parameters;
}
My guess is that It should check somewhere in the code for nil objects and remove theme. But I have really struggled with figuring out how to format the code.
I´m guessing the code should be something like this but I have no idea where to place it and how to format it.
NSMutableDictionary *dict = [parametersForCreateActivities mutableCopy];
NSArray *keysForNullValues = [dict allKeysForObject:[NSNull null]];
[dict removeObjectsForKeys:DefaultcreateImageID];
Try below code
NSMutableDictionary *yourDictionary; // Your dictionary object with data
NSMutableDictionary *updatedDic = [yourDictionary mutableCopy];
for (NSString *key in [yourDictionary allKeys]) {
if ([yourDictionary[key] isEqual:[NSNull null]] || [yourDictionary[key] isKindOfClass:[NSNull class]]) {
updatedDic[key] = #"";
}
}
yourDictionary = [updatedDic copy];
NSLog(#"%#",yourDictionary);

Is there a way to get all values in NSUserDefaults? [duplicate]

This question already has answers here:
Easy way to see saved NSUserDefaults?
(24 answers)
Closed 9 years ago.
I would like to print all values I saved via NSUserDefaults without supplying a specific Key.
Something like printing all values in an array using for loop. Is there a way to do so?
Objective C
all values:
NSLog(#"%#", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allValues]);
all keys:
NSLog(#"%#", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);
all keys and values:
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
using for:
NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];
for(NSString* key in keys){
// your code here
NSLog(#"value: %# forKey: %#",[[NSUserDefaults standardUserDefaults] valueForKey:key],key);
}
Swift
all values:
print(UserDefaults.standard.dictionaryRepresentation().values)
all keys:
print(UserDefaults.standard.dictionaryRepresentation().keys)
all keys and values:
print(UserDefaults.standard.dictionaryRepresentation())
You can use:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *defaultAsDic = [defaults dictionaryRepresentation];
NSArray *keyArr = [defaultAsDic allKeys];
for (NSString *key in keyArr)
{
NSLog(#"key [%#] => Value [%#]",key,[defaultAsDic valueForKey:key]);
}
Print only keys
NSLog(#"%#", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);
Keys and Values
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
You can log all of the contents available to your app using:
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

Storing Multiple value in MutableArray with different value

I have a button which on click I store the index of the current quotes into an array.
The problem is that it is overwriting the same object. How can I change it with different object of the NSNumber to store in the NSMutableArray?
[someButton setImage:[UIImage imageNamed:#"add_favoritegold.png"] forState:UIControlStateHighlighted];
NSUserDefaults *favoriteQuotes = [NSUserDefaults standardUserDefaults];
NSMutableArray *ListOfIndex= [[NSMutableArray alloc] init];
//Want to change with diffrent objecy
**NSNumber* Wrapped = [NSNumber numberWithInt:index];**
[ListOfIndex addObject:Wrapped];
int xOut = [[ListOfIndex lastObject] intValue];
NSLog(#"%d",xOut);
[favoriteQuotes setObject:ListOfIndex forKey:#"Indexes"];
Try this
- (void)saveFavouriteQuoteIndex:(NSUInteger)index
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *savedQuoteIndexes = [[defaults objectForKey:#"Indexes"]mutableCopy];
if (!savedQuoteIndexes) {
savedQuoteIndexes = [NSMutableArray array];
}
NSNumber *indexNumber = #(index);
if (![savedQuoteIndexes containsObject:indexNumber]) {
[savedQuoteIndexes addObject:indexNumber];
[defaults setObject:savedQuoteIndexes forKey:#"Indexes"];
[defaults synchronize];
}
}
You are saving ListOfIndex with key as Indexes.
So, for the next whatever value, it will replace previous value having key Indexes.
EDIT:
Read the array
NSArray *readArray=favoriteQuotes[#"Indexes"];
Add your new value into this same array.

find special keys in UserDefaults by "substringToIndex"

I'm grouping my UserDefault keys by specific prefixes.
e.g.
[NSUserDefaults standardUserDefaults] setInteger: 1 forKey: #"prefix1_someText_Key"]
[NSUserDefaults standardUserDefaults] setInteger: 2 forKey: #"prefix2_someText_Key"]
[NSUserDefaults standardUserDefaults] setInteger: 3 forKey: #"prefix4_someText_Key"]
//.....
Now, I'd like to find all the keys, that start with e.g. "prefix", and load them into an array. is there a way for doing that (programmatically)?
You could use the underlying NSDictionary to find the suitable keys:
NSString *myPrefix = #"prefix";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [defaults dictionaryRepresentation];
NSMutableArray *keysWithPrefix = [NSMutableArray array]
for (NSString *key in dict.keyEnumerator) {
if ([key hasPrefix: myPrefix]) {
[keysWithPrefix addObject: key];
}
}
// now keysWithPrefix contains all matching keys
UPDATE
For debugging reasons you could add a log to see what keys are being dropped:
for (NSString *key in dict.keyEnumerator) {
if ([key hasPrefix: myPrefix]) {
[keysWithPrefix addObject: key];
} else {
NSLog(#"Dropping key %#", key);
}
}

How to add NSUserDefault data to a UITextField?

I have 3 UIVIewControllers that have NSUsuerDefaults to store data. My 4th UIViewController is used to display the total data collected between the first 3 UIViewControllers. How do I collect the data and display it in a UITextfield? Here is an example of my NSUserDefault code that I'm using:
[tex setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue1"]];
[tex setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue22"]];
[tex setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue43"]]; I want to add this collected data to a UITextfield on my 4th UIViewController.
Try this:
textField.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue1"];
Or
NSString *storedValue1 = [[NSUserDefaults standardUserDefaults] objectForKey:#"storedTextValue1"];
textField.text = storedValue1;
I think you should use
tex setText:[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue43"];
So basically you need to use valueForKey: in place of objectForKey:
Hope this helps you.
EDIT:
[text setText:[NSString stringWithFormat:#"%# %# %#",[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue43"],[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue1"],[[NSUserDefaults standardUserDefaults] valueForKey:#"storedTextValue22"]]];
EDIT-2:
UITextField(Total) is Say txtTotal
UITextField(storetext1) is say txtStore1
UITextField(storetext2) is say txtStore2
UITextField(storetext3) is say txtStore3
Now simply do this as
int sum = [txtStore1.text intValue] + [txtStore2.text intValue] + [txtStore3.text intValue]
txtTotal.text = [NSString stringWithFormat:#%d",sum];