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);
Related
My brain is fried! I can't think.
i am new to iphone programming
am doing json parsing ....in that am storeing data from json to nsdictionary but .......
I want to add all nsdictionary float values from the dictionary to the array. This is what I am doing right now.As code below:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
dict = [responseString JSONValue];
NSMutableArray *array = [NSMutableArray array];
for (NSString *key in [dict allKeys])
{
array = [dict objectForKey:key];
// array return float values but
[array addObject:array ]; // geting carsh dude to array return float values like 120.01
}
Please guide me i am not getting a part where i am doing a mistake.
Thanks in advance.
Your app is crashing because you are adding data to NSArray , this is static array, you can not add value at run time, so just Make NSMutableArray and add your data in NSMutableArray.
Your code is broken in a couple of ways.
This line assigns the array pointer to the object in the dictionary:
array = [dict objectForKey:key];
Then you are trying to add the array to itself, which does not make sense. But worse, since array does no longer point to your NSMutableArray you cannot even call that method.
[array addObject:array ];
You probably wanted to do something like this:
for (NSString *key in [dict allKeys])
{
id value = [dict objectForKey:key];
[array addObject:value];
}
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).
The iPhone UIImagePickerControllerReferenceURL returns an URL as:
assets-library://asset/asset.PNG?id=1000000001&ext=PNG
What's the best (preferably simple) way to retrive 1000000001 and PNG as NSStrings from the above URL example?
Well, you can easily turn it into an NSURL by using +[NSURL URLWithString:]. From there you could grab the -query string and parse it out, something like this:
NSString *query = ...;
NSArray *queryPairs = [query componentsSeparatedByString:#"&"];
NSMutableDictionary *pairs = [NSMutableDictionary dictionary];
for (NSString *queryPair in queryPairs) {
NSArray *bits = [queryPair componentsSeparatedByString:#"="];
if ([bits count] != 2) { continue; }
NSString *key = [[bits objectAtIndex:0] stringByRemovingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *value = [[bits objectAtIndex:1] stringByRemovingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[pairs setObject:value forKey:key];
}
NSLog(#"%#", pairs);
Warning, typed in a browser, so some of my spellings may be wrong.
For IOS >= 4.0 you can use native regular expressions with NSRegularExpression class. Examples you can find here
NSMutableArray count is returning zero after adding objects to it, its been an hour of hacking away trying to figure out why, and I'm still stuck, so that brings me here.
Any ideas based off the following code, what the problem is?
the object 'search' is a custom class defined in the header set as a pointer, with retain, nonatomic attributes.
- (NSMutableArray *) populateArrayFromPlist{
NSLog(#"Populate Array from PList");
NSDictionary *dictionary;
// read "foo.plist" from application bundle
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"asearch.plist"];
dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];
for (id key in dictionary)
{
search = [[ASearch alloc] init];
[dictionary valueForKey:key];
[search setID:[[dictionary valueForKey:key] intValue] ];
//[[search searchString] initWithString: key];
search.searchString = [[NSMutableString alloc] initWithString: key];
if (search == nil) {
printf("Let me know now\n\n\n\n");
}
NSLog(#"%#", [search searchString]);
NSLog(#"Setting string Value: %s\n", [key cString]);
NSLog(#"Setting ID Value: %i\n", [[dictionary valueForKey:key] intValue]);
//NSLog(#"aSearchArray count == %i", [[aSearchArray count] intValue]);
[aSearchArray addObject:search];
NSLog(#"aSearchArray count == %i", [aSearchArray count] );
aSearchArray is a nil object that is the only reason why you are getting count as zero.
For more confirmation just create a new local array and try to add your object to it.
You will get a proper count
Does anyone know how to easily read a Dictionary type PSMultiValueSpecifier from NSUserDefault into a UITableView control and save changes back to NSUserDefaults using iPhone SDK 3.0? If so, can you post some specific code to efficiently do this?
First to better access the specifier values inside the bundle I used the following code to turn them into a dictionary.
NSString* settingsBundle = [[[NSBundle mainBundle]
pathForResource:#"Settings"
ofType:#"bundle"]
stringByAppendingPathComponent:#"Root.plist"];
NSDictionary* rootPlist = [NSDictionary dictionaryWithContentsOfFile:settingsBundle];
if (rootPlist == nil)
return nil;
NSArray* specifiers = [rootPlist objectForKey:#"PreferenceSpecifiers"];
NSDictionary *multiValueSpecifier = nil;
for (NSDictionary *specifier in specifiers)
{
if ([[specifier objectForKey:#"Key"] isEqualToString:speficierKey] == YES &&
[[specifier objectForKey:#"Type"] isEqualToString:#"PSMultiValueSpecifier"] == YES)
{
multiValueSpecifier = specifier;
break;
}
}
if (multiValueSpecifier == nil)
return nil;
NSArray* titlesArray = [multiValueSpecifier objectForKey:#"Titles"];
NSArray* valuesArray = [multiValueSpecifier objectForKey:#"Values"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:titlesArray
forKeys:valuesArray];
return dictionary;
Well now if from your UI you did select something you need to store the KEY and not the VALUE of the dictionary.
[[NSUserDefaults standardUserDefaults] setObject:dictionaryKey forKey:#"myMultiValueSpecifier_preference"];