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.

Labels:

0 Comments:

Post a Comment

<< Home