Skip to content

Instantly share code, notes, and snippets.

@cesteban
Last active August 29, 2015 14:21
Show Gist options
  • Save cesteban/b8b605f924eef73436e6 to your computer and use it in GitHub Desktop.
Save cesteban/b8b605f924eef73436e6 to your computer and use it in GitHub Desktop.
Crash due to LSP violation
@interface Shape : NSObject
@end
@interface Circle : Shape
@end
@interface Triangle : Shape
- (BOOL)isEquilateral;
@end
@protocol BagOfShapes <NSObject>
@property Shape *shape;
@end
@interface BagOfTriangles : NSObject <BagOfShapes>
@property Triangle *shape;
@end
// Now in some other part of your code you do:
BagOfTriangles *bagOfTriangles = [[BagOfTriangles alloc] init];
id<BagOfShapes> bagOfShapes = bagOfTriangles;
// Legal, Circle "is a" Shape, but you just got a Circle in a bag of triangles, be ready for the disaster
bagOfShapes.shape = [[Circle alloc] init];
// Crash: Unrecognized selector sent to instance
[bagOfTriangles.shape isEquilateral];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment