Extremely simple -- how to compare chars - objective-c

I shouldn't be struggling this much. I want to extract a character from a string and compare it to a char. Here's the offending line:
if ([url characterAtIndex:url.length - 4] == "=") {
NSString *test = [url substringFromIndex:url.length - 3];
return [test intValue];
} else {
NSString *test = [url substringFromIndex:url.length - 2];
return [test intValue];
}
On the if line it throws the error Comparison between pointer and integer ('int' and 'char *'), strange enough on it's own since there isn't a single int in that comparison.
A second error also pops, Result of comparison against string literal is unspecified (use strncmp instead).
I'd love help with this error, I have no idea why it's getting thrown and it's stopping me from getting to the real work of debugging network calls. Any help is greatly appreciated!

Change "=" to '='.
"=" is a C string.
'=' is a char.
BTW - characterAtIndex: returns a unichar which is an unsigned short.

Related

Objective-C NSString for loop with characterAtIndex

I'm trying to loop through a NSString, character by character, but I'm getting a EXC_BAD_ACCESS error. Do you have an idea how to do this right? I've been googling for hours now but can't figure it out.
Here is my code (.m):
self.textLength = [self.text length];
for (int position=0; position < self.textLength; position++) {
NSLog(#"%#", [self.text characterAtIndex:position]);
if ([[self.text characterAtIndex:position] isEqualToString:#"."]){
NSLog(#"it's a .");
}
}
Thanks a lot!
Characters are not object. characterAtIndex returns unichar, which is actually an integer type unsigned short. You need to use %C instead of %# in NSLog. Also character is not a NSString, so you can't send it isEqualToString. You need to use ch == '.' to compare ch against '.'.
unichar ch = [self.text characterAtIndex:position];
NSLog(#"%C", ch);
if (ch == '.') {} // single quotes around dot, not double quotes
Note that, 'a' is character, "a" is C string and #"a" is NSString. They all are different types.
When you are using %# with unichar ch in NSLog, it is trying to print an object from memory location ch which is invalid. Thus you are getting a EXC_BAD_ACCESS.
characterAtIndex: returns a unichar, so you should use NSLog(#"%C", ...) instead of #"%#".
You also cannot use isEqualToString for a unichar, just use == '.' is fine.
If you want to find the position of all '.'s, you can use rangeOfString. Refer to:
String Programming Guide: Searching, Comparing, and Sorting Strings
Position of a character in a NSString or NSMutableString
characterAtIndex: returns a unichar, which is declared as typedef unsigned short unichar; The format specifier you are using in your calls to NSLog are incorrect, you could just do NSLog(#"%u",[self.text characterAtIndex:position]); or NSLog(#"%C",[self.text characterAtIndex:position]); if you want the actual character to print out.
Also, as a result of unichar being defined the way that it is, it's not a string, so you cannot compare it to other strings. Try something like:
unichar textCharacter = '.';
if ([self.text characterAtPosition:position] == testCharacter) {
// do stuff
}
If you want to find the location of a character in a string you can use this:
NSUInteger position = [text rangeOfString:#"."].location;
if the character or text is not found you will get a NSNotFound:
if(position==NSNotFound)
NSLog(#"text not found!");

Converting NSNumber to NSString is not realy a string

I have got a problem with converting an NSNumber value to an NSString
MyPowerOnOrNot is an NSNumber witch can only return a 1 or 0
and myString is an NSString..
myString = [NSString stringWithFormat:#"%d", [myPowerOnOrNot stringValue]];
NSLog(#"%#",myString);
if(myString == #"1") {
[tablearrayPOWERSTATUS addObject:[NSString stringWithFormat:#"%#",#"ON"]];
}
else if(myString == #"0") {
[tablearrayPOWERSTATUS addObject:[NSString stringWithFormat:#"%#",#"OFF"]];
}
What is wrong with this?
The NSLog shows 0 or 1 in the console as a string but I can't check it if it is 1 or 0 in an if statement?
If doesn't jump into the statements when it actually should.. I really don't understand why this doesn't works..
Any help would be very nice!
A couple of problems
myString = [NSString stringWithFormat:#"%d", [myPowerOnOrNot stringValue]];
-stringValue sent to an NSNumber gives you a reference to a string. The format specifier %d is for the C int type. What would happen in this case is that myString would contain the address of the NSString returned by [myPowerOnOrNot stringValue]. Or, on 64 bit, it would return half of that address. You could actually use [myPowerOnOrNot stringValue] directly and avoid the relatively expensive -stringWithFormat:
if(myString == #"1")
myString and #"1" are not necessarily the same object. Your condition only checks that the references are identical. In general with Objective-C you should use -isEqual: for equality of objects, but as we know these are strings, you can use -isEqualToString:
if ([[myPowerOnOrNot stringValue] isEqualToString: #"1"])
Or even better, do a numeric comparison of your NSNumber converted to an int.
if ([myPowerOnOrNot intValue] == 1)
Finally if myPowerOnOrNot is not supposed to have any value other than 0 or 1, consider having a catchall else that asserts or throws an exception just in case myPowerOnOrNot accidentally gets set wrong by a bug.
"myString " is a reference to a string, not the value of the string itself.
The == operator will compare the reference to your string literal and so never return true.
Instead use
if( [myString isEqualToString:#"1"] )
This will compare the value of myString to "1"
In Objective C; you can't compare strings for equality using the == operator.
What you want to do here is as follows:
[tablearrayPOWERSTATUS addObject:([myPowerOnOrNot integerValue]?#"ON":#"OFF"])];
Compact, fast, delicious.

NSString comparison question

I am trying to test to see if an NSString has the letters "PDF" as the first 3 letters:
if ([[[profiles stringForKey:#"response"] characterAtIndex:0] isEqualToString:#"P"]) {
//TODO
}
I started with this approach to see if I could at least narrow it down to those strings that start with "P" but I am getting an error on this that reads: "Invalid receiver type 'unichar'" AND "Cast to pointer from integer of different size"
Am I getting these errors because I am using the isEqualToString comparison? Does that attach the terminating zero to "P"? I tried to use the "==" comparison but I was also getting an error with that method.
if ([profiles hasPrefix:#"PDF"]) {
NSLog(#"my string starts with \"PDF\"");
}
You want to use the method substringToIndex instead of characterAtIndex. characterAtIndex is returning a unichar which is not an objective-c object to which isEqualToString can be sent.
Here is something that worked for me:
NSString* testString = #"PDFDocument";
NSString* subString = [testString substringToIndex:3];
if ( [subString isEqualToString:#"PDF"] == YES )
{
NSLog( #"same" );
}

Objective-C: Initializing char with char at index of string

unichar myChar = [myString characterAtIndex:0];
[myNSMutableArray addObject:myChar];
I am trying to insert the first char of a string into an array, to create an array of chars. the first line does not give me an error. The second line however, provides the following error: warning: passing argument 1 of 'addObject:' makes pointer from integer without a cast
This also crashes the application with a "bad address" error. I thought this error was due to a problem with memory allocation. Can someone shed some light on this.
You can only add objects to an array. unichar is a primitive data type. You have to wrap it in an NSNumber. A unichar is an unsigned short, so you can use:
[myNSMutableArray addObject:[NSNumber numberWithUnsignedShort:[myString characterAtIndex:0]]];
One option would be to add the character to your array as a string:
unichar myChar = [myString characterAtIndex:0];
NSString * charString = [NSString stringWithFormat:#"%c", myChar];
[myNSMutableArray addObject:charString];
Note that this is probably overkill.

casting a NSString to char problem

i want to casting my NSString to a constant char
the code is shown below :
NSString *date = #"12/9/2009";
char datechar = [date UTF8String]
NSLog(#"%#",datechar);
however it return the warning
assignment makes integer from pointer without a cast
and cannot print the char properly,can somebody tell me what is the problem
Try something more like this:
NSString* date = #"12/9/2009";
char* datechar = [date UTF8String];
NSLog(#"%s", datechar);
You need to use char* instead of char, and you have to print C strings using %s not %# (%# is for objective-c id types only).
I think you want to use:
const char *datechar = [date UTF8String];
(note the * in there)
Your code has 2 problems:
1) "char datechar..." is a single-character, which would only hold one char / byte, and wouldn't hold the whole array that you are producing from your date/string object. Therefore, your line should have a (*) in-front of the variable to store multi characters rather than just the one.
2) After the above fix, you would still get a warning about (char *) vs (const char *), therefore, you would need to "cast" since they are technically the same results. Change the line of:
char datechar = [date UTF8String];
into
char *datechar = (char *)[date UTF8String];
Notice (char *) after the = sign, tells the compiler that the expression would return a (char *) as opposed to it's default (const char *).
I know you have already marked the answer earlier however, I thought I could contribute to explain the issues and how to fix in more details.
I hope this helps.
Kind Regards
Heider
I would add a * between char and datechar (and a %s instead of a %#):
NSString *date=#"12/9/2009"; char * datechar=[date UTF8String];
NSLog(#"%s",datechar);
I was suffering for a long time to convert NSString to char to use for this function
-(void)gpSendDTMF:(char) digit callID: (int)cid;
I have tried every answer of this question/many things from Google search but it did not work for me.
Finally I have got the solution.
Solution:
NSString *digit = #"5";
char dtmf;
char buf[2];
sprintf(buf, "%d", [digit integerValue]);
dtmf = buf[0];