Class Object is always null - ios

This is the method when my app complete the downloading with contact which is coming from server. In for loop I am using AIContactParsarModal class and using dictionary I am setting the objects, but every time object value is null.
Thanks for the help and any help will be appreciable. Here is my code.
- (void)donewithContact {
self.allPersonDetailsDict = [[NSMutableDictionary alloc]initWithCapacity:1];
NSMutableArray *allKeysArray = [[NSMutableArray alloc] init];
NSString *prefix;
NSString *searchContactString = [[NSUserDefaults standardUserDefaults] objectForKey:#"AdvanceSearch"];
if ([searchContactString isEqualToString:#"SpecialSearch"]) {
[self.allPersonDetailsDict removeAllObjects];
}
if (getContactArray.count == 0 ){
[noContactLabel setHidden:NO];
} else {
for (AIContactParsarModal *contact in getContactArray) {
NSLog(#"contact LAST NAMES ARE %#",contact.lastName);
prefix = [[contact.lastName substringWithRange:NSMakeRange(0, 1)] uppercaseString];
if ([allKeysArray containsObject:prefix]) {
NSMutableArray *conatctsWithPrefix = [_allPersonDetailsDict objectForKey:prefix];
[conatctsWithPrefix addObject:contact];
} else {
[allKeysArray addObject:prefix];
NSMutableArray *conatctsWithPrefix = [[NSMutableArray alloc] initWithObjects:contact,nil];
[self.allPersonDetailsDict setObject:conatctsWithPrefix forKey:prefix];
NSLog(#"conatctsWithPrefix %#",conatctsWithPrefix);
}
}
[noContactLabel setHidden:YES];
}
NSLog(#"All Names First characters are:%#", allKeysArray);
[self.contactTableView reloadData];
[HUD hide:YES];
}

May be you are getting null value in contact by which you are getting null in conatctsWithPrefix
first print values stored in contact.

Related

if condition is met but contents of if statement don't seem to execute

I am trying to do an if/else statement where it checks to see if an array is empty. It seems like the first condition is evaluated and not met, and so it moves to the else and executes. This is the output on the screen (iOS):
The name that you see is there because the else statement gets executed. However there are 3 other usernames with scores of 0 which aren't getting displayed. Here is the relevant conditional:
NSArray *keyArray = [yy allKeys];
for(NSString *keyd in keyArray) {
NSLog(#"yy objectforkey *********: %#", [[yy objectForKey:keyd] debugDescription]);
if(![yy objectForKey:keyd]){
NSMutableDictionary* entry = [NSMutableDictionary new];
NSLog(#"inside yy object for key count 0 *****####***##*#*#*#");
[tableData addObject:keyd];
[matchesForUser addObject:#"0"];
entry[#"username"] = keyd;
entry[#"matches"] = #"0";
[entries addObject:entry];
}
else {
NSMutableArray *locs = [[NSMutableArray alloc] initWithArray:[yy objectForKey:keyd]];
//NSString *outerouter;
//NSNumber *outeroutermatches = [NSNumber numberWithInt:0];
for(NSDictionary *outterar in locs) {
NSMutableDictionary* entry = [NSMutableDictionary new];
NSLog(#"%# outtererjar descriptiong ##(#(#(#(#(#(#(#(#(#((#", [outterar description]);
entry[#"username"] = keyd;
entry[#"matches"] = [outterar valueForKey:#"groupmatches"];
if([entries count] > 0) {
for(int counter = 0; counter < [entries count]; counter++) {
if([[[entries objectAtIndex:counter] valueForKey:#"matches"] intValue] < [[entry valueForKey:#"matches"] intValue]) {
NSLog(#"GETTING IN IFFFFFF ABOOOVVEEEEE ******8888888*********");
//NSMutableDictionary *stud = [[NSMutableDictionary alloc] initWithObjectsAndKeys:keyd, #"username", nil];
[matchesForUser addObject:[outterar objectForKey:#"groupmatches"]];
[tableData addObject:keyd];
NSLog(#"%# WHAT IS ENTRIES>>>!!!!??!?!?!", [[entries objectAtIndex:counter] valueForKey:#"username"]);
if([keyd isEqualToString:[[entries objectAtIndex:counter] valueForKey:#"username"]]) {
NSLog(#"GETTING IN IFFFFFF ******8888888*********");
[entries removeObjectAtIndex:counter];
[entries insertObject:entry atIndex:counter];
}
else {
[entries addObject:entry];
}
}
else {
[entries addObject:entry];
}
}
}
else {
[matchesForUser addObject:[outterar objectForKey:#"groupmatches"]];
[tableData addObject:keyd];
[entries addObject:entry];
}
}
}
}
_tableViewScore and tableData are both arrays which are used to populate the UIScrollView(s). The code inside the if statement should execute every time an empty object is found (they are arrays). The else runs, that is why you see the username with the score, but it seems like the if isn't getting executed when the array is null.
When I output the object I am checking for, an empty object looks like this:
yy objectforkey *********: <__NSArrayM 0x170454cd0>(
)
I just need to be able to identify when one of the objects is like that. Thanks!
The line
![yy objectForKey:keyd]
checks
does the key keyd not exist in the dictionary
which is of course always false because all keys returned by the property allKeys are guaranteed to exist and a value for an existing key cannot be nil by definition.
If you want to check if the array is empty you have to write
![[yy objectForKey:keyd] count]
PS: Consider to use more descriptive variable naming rather than yy

how to search and replace in NSDictionary?

I have a JSON that I converted into NSDictionary and now I want to search and replace some values in it but I have no idea how to to this,
{
"CODE":200,
"APICODERESULT":"USER_INTERESTS",
"MESSAGE":"user interests fetched successfully",
"VALUE":{
"Books":[
{
"key":"7",
"value":"Fiction",
"selected":true
},
{
"key":"8",
"value":"Romantic",
"selected":true
}
],
"Music":[
{
"key":"11",
"value":"Classical",
"selected":false
},
{
"key":"12",
"value":"Jazz",
"selected":false
},
{
"key":"10",
"value":"Pop",
"selected":false
},
{
"key":"13",
"value":"Western",
"selected":false
}
]
}
}
here I have the value for key that I want to search in the dictionary and when I found that key with the value that I have I want to replace the value for selected in the same block.
For example:-
I have value 10 for key then I want to change the value for key selected to true
so the it will look like this
{
"CODE":200,
"APICODERESULT":"USER_INTERESTS",
"MESSAGE":"user interests fetched successfully",
"VALUE":{
"Books":[
{
"key":"7",
"value":"Fiction",
"selected":true
},
{
"key":"8",
"value":"Romantic",
"selected":true
}
],
"Music":[
{
"key":"11",
"value":"Classical",
"selected":false
},
{
"key":"12",
"value":"Jazz",
"selected":false
},
{
"key":"10",
"value":"Pop",
"selected":true
},
{
"key":"13",
"value":"Western",
"selected":false
}
]
}
}
Consider your input dictionary as mainDictionary and use following code:
NSMutableDictionary *valuesDic = [mainDictionary objectForKey:#"VALUES"];
NSArray *allPossibleKeysArray = [valuesDic allKeys];
for (int j=0; j<allPossibleKeysArray.count; j++) {
NSString *keyStr = [allPossibleKeysArray objectAtIndex:j];
NSArray *array = [valuesDic objectForKey:keyStr];
for (int i=0; i<array.count; i++) {
NSMutableDictionary *dictionary = [array objectAtIndex:i];
NSString *keyString = [NSString stringWithFormat:#"%#",[dictionary objectForKey:#"key"]];
if([keyString isEqualToString:keyvalue]){
[dictionary removeObjectForKey:#"selected"];
[dictionary setObject:[NSNumber numberWithBool:true] forKey:#"selected"];
}
}
}
Hope this helps!!
You should make such changes during parsing the JSON/moving it into model. The code below is a workaround:
NSDictionary *initialJson = //Your JSON here
NSArray *allSubKeys= [initialJson[#"Value"] allKeys];
// Your mutable output.
NSMutableDictionary *mutableJson = [initialJson mutableCopy]
for(NSString *key in allSubKeys) {//Music && Books
// Create another cointainer here
for(NSArray *arr in mutableJson[#"Value][key]) {
// Create another cointainer here
for(NSDictionary *dict in arr) {//key, value, selected
for (NSString *key2 in [dict allKeys]) {
if ([key2 isEqualToString:#"selected"] && [dict[#"value"] equals:#10]) {
// Save YES here
}
else {
// Just copy element
}
// Add object to parent container
}
// Add object to parent container
}
// Add object to parent container
}
// Add object to parent container
}
Here is full solution
NSString* str=#"{\"CODE\":200,\"APICODERESULT\":\"USER_INTERESTS\",\"MESSAGE\":\"user interests fetched successfully\",\"value\":{\"Books\":[{\"key\":\"7\",\"value\":\"Fiction\",\"selected\":true},{\"key\":\"8\",\"value\":\"Romantic\",\"selected\":true}],\"Music\":[{\"key\":\"11\",\"value\":\"Classical\",\"selected\":false},{\"key\":\"12\",\"value\":\"Jazz\",\"selected\":false},{\"key\":\"10\",\"value\":\"Pop\",\"selected\":false},{\"key\":\"13\",\"value\":\"Western\",\"selected\":false}]}}";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"dictionary before updating: %#", dictionary);
// copy old dict
NSMutableDictionary* newDict=[[[NSMutableDictionary alloc]init]autorelease];
[newDict addEntriesFromDictionary:dictionary];
// get the entry to be changed
NSMutableDictionary* valueDict=[[[NSMutableDictionary alloc]init]autorelease];
[valueDict addEntriesFromDictionary:newDict[#"value"]];
NSMutableArray* musicArray=[[[NSMutableArray alloc] init] autorelease];
[musicArray addObjectsFromArray:newDict[#"value"][#"Music"]];
// get the music array and change your property
NSMutableDictionary* musicDict2=[[[NSMutableDictionary alloc] init] autorelease];
[musicDict2 addEntriesFromDictionary:[musicArray objectAtIndex:2]];
[musicDict2 setValue:[NSNumber numberWithBool:YES] forKey:#"selected"];
[musicArray replaceObjectAtIndex:2 withObject:musicDict2];
// update the value dictionary
[valueDict setObject:musicArray forKey:#"Music"];
//update the new dictionary
[newDict setObject:valueDict forKey:#"value"];
NSLog(#"dictionary after updating: %#", newDict);

empty json reponse in Foursquare2 venue Explore ios api

I'm working on iOS application with foursquare iOS api , I want to get the recommended near venues. I have used following code & it giving me an empty result .. Where have I done the mistake ? ? ?
NSArray* venues;
//get the foursquare locations
- (void)getTipsForLocation:(CLLocation *)location {
//NSLog(#"lat %f",location.coordinate.latitude);
[Foursquare2 venueExploreRecommendedNearByLatitude:#(location.coordinate.latitude)
longitude:#(location.coordinate.longitude)
near:nil
accuracyLL:nil
altitude:nil
accuracyAlt:nil
query:nil
limit:nil
offset:nil
radius:#(1500)
section:nil
novelty:nil
sortByDistance:1
openNow:0
venuePhotos:0
price:nil
callback:^(BOOL success, id result){
if (success) {
NSDictionary *dic = result;
venues = [dic valueForKeyPath:#"response.venues"];
FSConverter *converter = [[FSConverter alloc]init];
self.nearbyVenues = [converter convertToObjects:venues];
//NSLog(#"venues %#",venues);
//NSLog(#"near by places %#",self.nearbyVenues);
}
else{
NSLog(#" foursquare connecting error");
}
}];
NSLog(#"recommended place array %#",venues);
}
You Can Not pass Nil,In NSNumber & NSString.
NSNumber *emptynumber=[[NSNumber alloc] init];
[Foursquare2 venueExploreRecommendedNearByLatitude:lan longitude:lon near:#"" accuracyLL:emptynumber altitude:emptynumber accuracyAlt:emptynumber query:#"" limit:emptynumber offset:emptynumber radius:#(1500) section:#"" novelty:#"" sortByDistance:YES openNow:YES venuePhotos:YES price:#"" callback:^(BOOL success, id result) {
if (success) {
NSLog(#"secondResult: %#",result);
NSDictionary *dic = result;
NSArray *venues = [dic valueForKeyPath:#"response.venues"];
FSConverter *converter = [[FSConverter alloc] init];
self.venues = [converter convertToObjects:venues];
[self.tableView reloadData];
NSLog(#"Data: %#",venues);
}
}];
It Works For me.

How can i read first item inside multiple arrays in IOS

I have this Array, and i need all first elements.
I can only read one with this
vc.ArrayListaFotos = [[listaImagens objectAtIndex:(indexPath.row * 3)] valueForKey:#"Caminho"];
But I can't read others first itens inside array 1,2,3...
Can someone help me please ?
You are using the wrong reference. You should do that:
NSMutableArray *arrayDeImagensParaOProdutoSelecionado = [NSMutableArray arrayWithObjects:nil];
for (NSArray *tempArray in listaImagens) {
if ([[NSString stringWithFormat:#"%#", [tempArray valueForKey:#"idProduto"]] isEqualToString:[NSString stringWithFormat:#"%#", [[produtos objectAtIndex:(indexPath.row * 3)] valueForKey:#"id"]]]) {
[arrayDeImagensParaOProdutoSelecionado addObject:tempArray];
}
}
Hope it help.
for(NSArray *innerArray in outerArray) {
NSObject *firstObject = [innerArray firstObject];
// do whatever you need to with firstObject
NSLog(#"%#",firstObject);
}

Why is my array returning null?

I am calling getBoardingCards once here:
BRPBoardingCards *boardingCards = [[BRPBoardingCards alloc] init];
boardingCardsArray = [boardingCards getBoardingCards];
The array is returning null though (in the NSLog shown). What am I doing wrong?
- (NSArray*)getBoardingCards
{
NSMutableArray *storedArray = [[NSMutableArray alloc] init];
Utils *utils = [[Utils alloc] init];
NSUserDefaults *properties = [utils getUserDefaults];
// check if its the first time we are running the app.
if(![[properties objectForKey:#"first_run"] isEqualToString:#"no"]){
//I decided it is for american tourists and every booking office allows payment in dollars because I dont have a euros key on my keyboard.
//Car also has lots of seats. 1337 of them to be precise.
[self setNewBoardingCardWithCardType:#"car" WithPrice:#"$1.50" AndStartLocation:#"airport" AndEndLocation:#"restaurant" WithSeat:#"1337" andExtraInformation:#"We dont like you so we are giving you the back seat by yourself."];
[self setNewBoardingCardWithCardType:#"helicopter" WithPrice:#"$500" AndStartLocation:#"restaurant" AndEndLocation:#"hospital" WithSeat:#"1" andExtraInformation:#"You are driving."];
[self setNewBoardingCardWithCardType:#"train" WithPrice:#"$100" AndStartLocation:#"restaurant" AndEndLocation:#"ditch" WithSeat:#"STANDONHEAD" andExtraInformation:#"No Seats on this train. Gotta stand on your head. Dont forget your white lightning for the ditch."];
[self setNewBoardingCardWithCardType:#"Fire Engine" WithPrice:#"$10" AndStartLocation:#"restaurant" AndEndLocation:#"burning house" WithSeat:#"HOSE" andExtraInformation:#"Take the hose to put out this fire we are heading to. "];
[self setNewBoardingCardWithCardType:#"Nimbus" WithPrice:#"$300" AndStartLocation:#"burning house" AndEndLocation:#"popo floating island" WithSeat:#"LEVITATION" andExtraInformation:#"Dont forget to turn super saiyan on your way up there. "];
[self setNewBoardingCardWithCardType:#"Sky Dive" WithPrice:#"$1020" AndStartLocation:#"popo floating island" AndEndLocation:#"home" WithSeat:#"GRAVITY" andExtraInformation:#"Ohh! that Adrenalines pumping. "];
[self setNewBoardingCardWithCardType:#"Legs" WithPrice:#"$50" AndStartLocation:#"ditch" AndEndLocation:#"park bench hotel" WithSeat:#"VODKA" andExtraInformation:#"Time to get a good nights rest and sobre up. "];
[self setNewBoardingCardWithCardType:#"Bicycle" WithPrice:#"$5" AndStartLocation:#"park bench hotel" AndEndLocation:#"home" WithSeat:#"BIKESEAT1" andExtraInformation:#"What a terrible hangover. Time to head home. "];
[self setNewBoardingCardWithCardType:#"ambulance" WithPrice:#"$40" AndStartLocation:#"hospital" AndEndLocation:#"home" WithSeat:#"LEVITATION" andExtraInformation:#"Well that was a bad idea! "];
[properties setObject:#"no" forKey:#"first_run"];
[properties synchronize];
NSLog(#"did set first run to no");
}
storedArray = [[properties objectForKey:#"cards"] mutableCopy];
NSLog(#"getBoardingCards storedArray: %#", storedArray);
return storedArray;
}
- (NSArray*)getBoardingCardsByType:(NSString*)cardType
{
// at this point i would create a for loop and iterate through the array checking if (type isEqualToString:cardType).
// But this is just an idea for later. To go by only a certain type of route.
return nil;
}
- (void)setNewBoardingCardWithCardType:(NSString*)cardType WithPrice:(NSString*)price AndStartLocation:(NSString*)startLocation AndEndLocation:(NSString*)endLocation WithSeat:(NSString*)seatCode andExtraInformation:(NSString*)extraInfo{
// populate the dictionary with data.
NSMutableDictionary *card = [[NSMutableDictionary alloc] init];
[card setObject:cardType forKey:#"type"];
[card setObject:price forKey:#"price"];
[card setObject:startLocation forKey:#"startLocation"];
[card setObject:endLocation forKey:#"endLocation"];
[card setObject:seatCode forKey:#"seat"];
[card setObject:extraInfo forKey:#"info"];
// get our stored array.
Utils *utils = [[Utils alloc] init];
NSUserDefaults *properties = [utils getUserDefaults];
NSMutableArray *storedArray = [[properties objectForKey:#"cards"] mutableCopy];
[storedArray addObject:card];
// set the stored array.
[properties setObject:storedArray forKey:#"cards"];
[properties synchronize];
}
You're not creating the cards mutable array in the NSUserDefaults.
This line (in setNewBoardingCardWithCardType:):
NSMutableArray *storedArray = [[properties objectForKey:#"cards"] mutableCopy];
is essentially
NSMutableArray *storedArray = [nil mutableCopy];
which is the same as
NSMutableArray *storedArray = nil;
Check if the object for this key exist, if not - create it and then use it.

Resources