views:

39

answers:

2

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.

+2  A: 
if ([profiles hasPrefix:@"PDF"]) {
  NSLog(@"my string starts with \"PDF\"");
}
Dave DeLong
+1  A: 

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" );
}
ericgorr
Yep, hasPrefix works too.
ericgorr
+1 except that this would fail with multi-byte-character languages.
Dave DeLong