Home > DeveloperSection > Forums > Issue with NSString method initWithData: encoding: in Objective-C
Jayne Spooner
Jayne Spooner

Total Post:21

Posted on    December-13-2015 11:30 PM

 iPhone iPhone  Ios  Objective C 

 1 Reply(s)
 389  View(s)
Rate this:

I have an issue with the initWithData: method of NSString, here is code:

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

Here, problem with initWithData: is that it does't return an instance of NSString, I tried doing an explicit type-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.

Tarun Kumar

Total Post:214

Posted on    December-14-2015 11:47 PM

I noticed that there is a type mismatch from the compiler. When you are trying to use strObj 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:

CustomClass *customObj;
NSString *strObj;
strObj = [[NSString alloc] initWithData:dataObj encoding:NSUTF8StringEncoding];
[customObj methodWithString:strObj];

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 will be happen if CustomClass is forward declared in a header file (as @class CustomClass) but never subsequently included in the implementation file.

Don't want to miss updates? Please click the below button!

Follow MindStick