Can't compare values in if statement - ios

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])

Related

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];

Check whether the NSArray object at index is of kind NSString Or NSNumber

This is my NSArray :
(
"tag_name",
3,
"mp4_url",
4,
0,
"back_tag",
5,
1,
"part_id",
"related_list",
2
)
I need to put all the numerical values in some another array.
I used the following code to check whether the value fetched from the array was a numeric or a string, but it didn't work. Every time i get the value from an array as NSString.
for (int i=0; i<arr.count; i++) {
id obj=[arr objectAtIndex:i];
if ([obj isKindOfClass:[NSString class]])
{
// It's an NSString, do something with it...
NSLog(#"its string");
}else{
// It's an Numerical value, do something with it...
NSLog(#"its integer value");
}
}
I know that array stores only kind of objects in it, so while fetching i'm getting the value as NSString(i.e object). But is there anyway to check whether the value stored was a numeric value.
Please can anyone help me..
Thanks
You can't just turn an NSString into an NSNumber but there are ways that you can try to get he numeric value out of them.
This is one option but you could also have a look at NSNumberFormatter.
If all of the numbers are integers then you could do something like this...
// always use fast enumeration
for (NSString *string in arr) {
NSInteger integer = [string integerValue];
// have to check explicitly for 0 as a non-numeric would return 0 above
if ([string isEqualToString:#"0"]
|| integer != 0) {
// it is an integer numeric string
} else {
// it is a string
}
}

Check if an item exists then replace it in NSMutableArray

how do i check if an item exists and if it does replace it in NSMutableArray i just cant figure it out all i have so far is:
int i = [arrayOne indexOfObject:#"object to replace"];
NSLog(#"%#", i);
[arrayOne replaceObjectAtIndex:i withObject:#"replace"];
but i keep getting errors :S can anyone help me ?
My array is:
#[ "13L6-A67-1", "13NAPUSD-A1", "13NASUWO-X1", "13NASUWO-X1", "13ASECON-D1", "13ASECON-D1", "13ASECON-D1", "13ASECON-D1", "13ASMATH-C1", "13ASMATH-C1", "13ASMATH-C1", "13ASMATH-C1", "13ASPHYS-B1", "13ASPHYS-B1", "13ASPHYS-B1", "13ASPHYS-B1", "13B3ITCE-F1", "13B3ITCE-F1", "13B3ITCE-F1", "13B3ITCE-F1" ]
if object is not present in array NSNotFound value is returned, so you need to check for it:
if (i != NSNotFound)
[arrayOne replaceObjectAtIndex:i withObject:#"replace"];
Note also that if you want to print integer value, you should use %d format specifier, %# is used for objective-c objects
It seems you are new to this platform. So here is the sample code that works -
NSMutableArray *arrayOne = [#[#"13L6-A67-1",#"13NAPUSD-A1",#"13NASUWO-X1",#"13NASUWO-X1",#"13ASECON-D1",#"13ASECON-D1",#"13ASECON-D1",#"13ASECON-D1",#"13ASMATH-C1",#"13ASMATH-C1",#"13ASMATH-C1",#"13ASMATH-C1",#"13ASPHYS-B1",#"13ASPHYS-B1",#"13ASPHYS-B1",#"13ASPHYS-B1",#"13B3ITCE-F1",#"13B3ITCE-F1",#"13B3ITCE-F1",#"13B3ITCE-F1" ] mutableCopy];
NSUInteger index = [arrayOne indexOfObject:#"13ASECON-D1"];
if (index != NSNotFound) {
[arrayOne replaceObjectAtIndex:index withObject:#"DIFFERENT_VALUE"];
NSLog(#"arrayOne after replaceObjectAtIndex = %#", arrayOne);
}
General guidelines -
watch out for compiler warning when you build.
put breakpoint and step through your code which doesn't work.

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

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).

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