ISSUE WITH NSSTRING METHOD INITWITHDATA: ENCODING: IN OBJECTIVE-C

Jayne Spooner

Total Post:21

Points:147
Posted by  Jayne Spooner
 435  View(s)
Ratings:
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.

  1. Tarun Kumar

    Post:214

    Points:1642
    Re: Issue with NSString method initWithData: encoding: in Objective-C

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!