0

I set an incompatible pointer type, but the code works ok. I want to know the reason. X1 is the exact copy of X2 code.

@interface ViewController : UIViewController

@property(retain,nonatomic) X1 *testProperty;

@end

// ###############################

@implementation ViewController

@synthesize testProperty;

   - (void)viewDidLoad {
      [super viewDidLoad];

      testProperty = [X2 new];  --> Warning
      [testProperty printLog];
   }
}

The warning is: Incompatible pointer types assigning to
This warning is obvious, but my problem is how this code works ok? does it cast it?

Fattaneh Talebi
  • 727
  • 1
  • 16
  • 42

1 Answers1

2

This works because of the dynamic nature of Objective-C. The compiler correctly warns you about mismatching types, but at runtime, when it executes the message sending of printLog to its receiver, it checks if the object actually knows how to handle this message. Since both your X1 and X2 classes implement printLog, this works. Likewise, any messsage that is implemented in any commmon superclass of X1 and X2 (so at least everything from NSObject) would also work.

This is called "Duck Typing" and is really fundamental to the ObjC runtime.

Gereon
  • 17,258
  • 4
  • 42
  • 73
  • @Fattaneh Talebi please also bear in mind that in general this is a very dangerous way of acting, because it can take you to unpredictable behaviour. Let's say for example that in a distant future you modify X2 and remove the printLog method (assuming they are *not* sibling subclasses with that method implemented in the parent class): the compiler won't warn you about that, but the app will just crash when trying to call it – il3v Dec 24 '18 at 11:10