Friday, July 25, 2008

warning: initialization from distinct Objective-c type (iPhone Development)

This warning is raised by Xcode whenever an implicit or INCORRECT type cast is occurring.
(The AS3 equivilant is the error: Error # 1067: Implicit coercion of a value of type * to an unrelated type *.)

"Distinct Objective-C type" is the type id. Apple docs say, "In Objective-C, object identifiers are a distinct data type: id. This type is defined as a pointer to an object..."

Example Causes:
NSMutableArray* myArraySorted = [myArray sortedArrayUsingSelector:@selector(compare:)];

The above will raise "warning: initialization from distinct Objective-c type" because sortedArrayUsingSelector returns an object of type id. We can correct this by simply casting the return value to the type NSMutableArray* as follows.

NSMutableArray* myArraySorted = (
NSMutableArray*)[myArray sortedArrayUsingSelector:@selector(compare:)];

Finally notice that the incorrect cast that follows will also raise this warning:
NSMutableArray* myArraySorted = (NSString*)[myArray sortedArrayUsingSelector:@selector(compare:)];
Hence, whenever you see: "warning: initialization from distinct Objective-c type" you are performing an implicit cast.

4 comments:

  1. Thanks, you've just saved a lot of my time :)
    ReplyDelete
  2. Thanks for the post. I get what you're trying to say but I must be slow because I don't know how to fix the warning in the project I'm working on. I downloaded this sample project from icodeblog.com.

    I haven't changed anything, so you should be able to open up the project and take a look. What do I need to change in the project?
    ReplyDelete
  3. this helped ! thanks :) i kept on getting it from writing

    MKPinAnnotationView *view = [mView dequeueReusableAnnotationViewWithIdentifier:@"PIN_ANNOTATION"];

    then thanks to you..i changed to

    MKPinAnnotationView *view = (MKPinAnnotationView *)[mView dequeueReusableAnnotationViewWithIdentifier:@"PIN_ANNOTATION"];
    ReplyDelete
  4. thanks . it solved my problem.
    ReplyDelete