Searching dictionary works find with hard coded variable, but otherwise crashes - ios

I have the following code to search the following dictionary:
//NSString *knownObject = #"3:40 am";
NSArray *temp = [itemDict allKeysForObject:knownObject];
NSString *key = [temp objectAtIndex:0];
NSLog(#"prayer: %#", key);
Dict:
{
asr = "4:23 pm";
dhuhr = "12:02 pm";
fajr = "1:16 am";
isha = "10:47 pm";
maghrib = "8:24 pm";
shurooq = "3:40 am";
}
When running the first line, it correctly returns "shurooq". However, when I use my variable:
NSArray *temp = [itemDict allKeysForObject:nextPrayerTime];
The log output of nextPrayerTime is simply 3:40 am as expected.
Why is this not working?
Many thanks!

Checkout the value of nextPrayerTime, if itemDict contain any object same as nextPrayerTime then [itemDict allKeysForObject:nextPrayerTime]; will return an array of keys otherwise it will return empty array.
In your current case anyhow you get an empty array but when you try to access [temp objectAtIndex:0] then compiler couldn't find any object and it gets an array out of bound exception and this cause the crash of your app....
To overcome this exception you should check the count of objects in array...
NSArray *temp = [itemDict allKeysForObject: nextPrayerTime];
if([temp count] > 0) {
NSString *key = [temp objectAtIndex:0];
NSLog(#"prayer: %#", key);
} else
NSLog(#"NO Object Found");

What is the value of nextPrayerTime?
According to the docs, allKeysForObject: returns
A new array containing the keys corresponding to all occurrences of anObject in the dictionary. If no object matching anObject is found, returns an empty array.
Based on the information given I would guess you are getting back an empty array and when you call [temp objectAtIndex:0] you are accessing an index that does not exist and getting an out of bounds exception.

I am not a 100% sure of my answer, but is the method isEqualToString used for comparison of the objects when the object is a NSString?
Otherwise you probably need to compare to the original object in the dictionary (using the same NSString).

Related

Can't compare values in if statement

I'm new to ios. I want to check if statement is true, but this condition gives true everytime even when it's false.
NSMutableArray *passengers=loginObj.passengers;
PassengerObj *passenger=[passengers objectAtIndex:0];
if([[passenger checkedIn] objectAtIndex:0])
{
[somestatement];
}
in debugger
_checkedIn __NSCFArray * #"1 object" 0x168b8200
>[0] __NSCFBoolean * #"0" 0x37e696d4
Assuming your array only contains strings that contain a 1 or a 0, you can compare the string:
if ([[[passenger checkedIn] objectAtIndex:0] isEqualToString:#"0"])
Of course it would be more readable to have an array of NSNumbers and use
if ([[[passenger checkedIn] objectAtIndex:0] boolValue])

IOS NSDictionary element to NSString

Hi I am trying to extract key value from NSDictionary, the dictionary value looks like below screen shot
I need to extract the value with key "TITLE" to NSString, using the code
NSDictionary* tmp = [self getDBRequest:req];
NSString * title =[tmp valueForKey:#"TITLE"];
But giving the the value like
Is there anything wrong with above code?
Edit:
NSLog(#"%#", tmp);
Gives the output
2015-12-31 11:04:52.530 SimpleTable[610:10059] (
{
DESCRIPTION = "30% OFF ON NEW ";
"IMAGE_URL" = "crowd.jpg";
TITLE = "GET 30% OFF";
}
)
Edit2
Actualy using the result of NSString * title =[tmp valueForKey:#"TITLE"]; I have to replace an element of NSMutableArray
And the code
NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:#"Eezy"];
[array addObject:#"Tutorials"];
NSDictionary* tmp = [self getDBRequest:req];
NSString * title =[tmp valueForKey:#"TITLE"];
[array replaceObjectAtIndex:0 withObject:title];
Giving me the array modified some thing like below screen shot
Look at the first image in your question, the first line of the contents dump says "1 object".
Also look at the output of the NSLog, notice the parentheses (( & )) which surround the braces ({ & }), which in turn surround the key/value pairs.
Both these are telling you that tmp is not referencing an NSDictionary as you think, but an NSArray containing a single element and that element is an NSDictionary.
Now when you invoke valueForKey: on an array of dictionaries it does the key lookup on every dictionary in the collection and returns and array of results.
Which is why when you look at the second image in your question you see that its contents dump also starts with "1 object" - title is referencing an array containing one element, being your string.
This is also why, as mentioned in the comments, that using objectForKey: in place of valueForKey: causes an error - that method does not operate on arrays and so produces the unrecognized selector sent to instance error.
HTH
try like bellow code.
NSDictionary *tmp = #{#"DESCRIPTION" : #"30 OFF ON NEW",#"IMAGE_URL" : #"crowd.jpg",#"TITLE" : #"GET 30% OFF"};
//NSDictionary* tmp = [self getDBRequest:req];
NSArray *keyArray = [tmp allKeys];
NSString * title = [keyArray objectAtIndex:[keyArray indexOfObject:#"TITLE"]];//[keyArray objectAtIndex:0];
[array replaceObjectAtIndex:0 withObject:title];

iOS How Array objects separated by commas convert into string?

I have an array named as child_list like child_list: "9,8,21,22,20,24,25", take it in NSString at index 0 when I convert it into string its work but when i use NSMutableArray it crashed, I don't know why.
My code is here:
if([theDictionary objectForKey:#"child_list"])
{
NSString *str = [[theDictionary objectForKey:#"child_list"]objectAtIndex:0];
NSLog(#"Child List %#",str);
_child_list = [[NSMutableArray alloc ]initWithObjects: [str componentsSeparatedByString:#","], nil];
}
When break point come on str it show result when it comes on _child_list it crashed.
Use initWithArray method while allocating _child_list NSMutableArray
if([theDictionary objectForKey:#"child_list"])
{
NSString *str = [[theDictionary objectForKey:#"child_list"]objectAtIndex:0];
NSLog(#"Child List %#",str);
_child_list = [[NSMutableArray alloc ] initWithArray:[str componentsSeparatedByString:#","]];
}
Please share what your log returns and the dictionary you used..
The code [str componentsSeparatedByString:#","] returns an Array. So, when you're allocating a mutable array, you're creating array of array... Instead using initWithObjects, use initWithArray method and pass [str componentsSeparatedByString:#","] to it.

Interrogating an NSArray that appears to have a null entry

I have an iPad app that links to an SQL database to retrieve information in the following way:
NSString *strGetCodeUrl = [NSString stringWithFormat:#"%#", #"http://website/getdevicecode.php?device=" , deviceName];
NSArray *deviceArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strGetCodeUrl]];
This works when there is a device that matches and it retrieves the required information. However if there is not a match it returns
("")
The array however appears to have one record. Ideally I would like to stop this from happening and for the array to be empty if there is no match. Alternatively (although not very tidy) I could check the length of the entry at index 0 but I am struggling with this method.
NSString *deviceCode = [deviceArray objectAtIndex:0];
if ( [deviceCode length] == 0)
{
device does not exist
}
Any advice gratefully received.
What about this:
NSString *deviceCode = [deviceArray objectAtIndex:0];
if ([deviceCode isEqualToString:#""])
{
device does not exist
}
I don't think you can tell the init method to leave out empty strings...
However, you can do this:
NSString *strGetCodeUrl = [NSString stringWithFormat:#"%#", #"http://website/getdevicecode.php?device=" , deviceName];
NSArray *deviceArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strGetCodeUrl]];
[deviceArray removeObject:#""];
Which also isn't as tidy as perhaps you were hoping for, but it will remove all empty strings. But at least its just 1 line of code as opposed to about 3 for the if
Per the documentation:
Removes all occurrences in the array of a given object.

IF statement issue in IOS using NSString

My if statement won't work. active returns 1 but will not work in the IF statement
JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
NSDictionary *dict = [jsonKitDecoder objectWithData:jsonData];
NSString *userid = [dict valueForKeyPath:#"users.user_id"];
NSString *active = [dict valueForKeyPath:#"users.active"];
NSLog(#"%#",userid); // 2013-06-20 03:03:21.864 test[81783:c07] (74)
NSLog(#"%#",active); // 2013-06-20 03:03:21.864 test[81783:c07] (1)
if ([active isEqualToString:#"1"]){
// Do something
}
I can't seem to get this IF to work. Do I need to change the NSString to a int?
For starters, use a modern style for retrieving values from dictionaries, rather than valueForKeyPath:.
NSDictionary* users = dict[#"users"];
id active = users[#"active"];
Once you're using a modern style, my guess is that the active value is actually an NSNumber representing a boolean value. So your if block would read:
if([active isKindOfClass:NSNumber] && [active boolValue]) {
//active is an NSNumber, and the user is active
}
The syntax of your if statement is just fine. I would try the alternate method for retrieving values from a dictionary as mentioned above.
NSString *active = #"1";
if ([active isEqualToString:#"1"])
{
// Do something
NSLog(#"It works!");
}
More than likely the "users.active" object being returned from that NSDictionary-ized JSON stream is a "BOOL" or a "NSInteger" as the payload of a NSNumber object and it's not a NSString object.
Try using:
NSNumber * activeNumber = [dict valueForKeyPath: #"users.active"];
and see if "if ([activeNumber boolValue] == YES)" works better for you.

Resources