views:

3463

answers:

2

I have a couple of lines of trivial code such as the following:

NSData *dataReply;
NSString *stringReply;
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];

The problem here is, initWithData:encoding: does not return an instance of NSString as the documentation claims it does. I've tried doing an explicit cast using (NSString *) as well without much luck. This is giving me compiler warnings when I try to pass the stringReply to a method I've written with type mismatches. Given I treat all warnings as errors, I'd really like to understand what stringReply is being returned as and how I can enforce it to be of type NSString.

A: 

Not really sure what's going on, I ran the code below and got an NSString returned. Switching out the data with nil also works fine.

const char* os = "12345";
NSString* str = [[NSString alloc] initWithData:[NSData dataWithBytes:os length:5 ] encoding:NSUTF8StringEncoding];  
NSLog(@"%@", str);

If you debug it can you tell what type of object is being created?

Might help if you post the compiler warning.

Max Stewart
+5  A: 

A "type mismatch" from the compiler when you try to use stringReply in another location has nothing to do with the object being returned from initWithData:encoding: and everything to do with where stringReply is subsequently being used.

For example, if you are getting a type mismatch when you do this:

SomeClass *someObject;
NSString *stringReply;
stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];
[someObject methodWithString:stringReply];

The problem is not that initWithData:encoding: is returning the wrong type but one of:

  • methodWithString: doesn't actually take an NSString*
  • methodWithString: is not properly declared/included before being used

The second option can often happen if SomeClass is forward declared in a header file (as @class SomeClass) but never subsequently included in the implementation file.

Matt Gallagher