I'm trying to understand why this crashes when I use self.propName
notation but not when I use _ivarName
notation. Happy to learn about another part of Objective-C. Thanks for the help!
// .h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface FOOMySpecialClass : NSObject
@property (nonatomic, readonly, assign) BOOL isFoo;
- (void)setIsFoo:(BOOL)isFoo;
@end
NS_ASSUME_NONNULL_END
// .m
#import "FOOMySpecialClass.h"
@interface FOOMySpecialClass()
@property (nonatomic, readwrite, assign) BOOL isFoo;
@end
@implementation FOOMySpecialClass
- (void)setIsFoo:(BOOL)isFoo {
self.isFoo = isFoo; // <-- Crash here
}
@end
But, if I change the bool to the ivar, things work fine. I'm trying to understand why.
// .m
#import "FOOMySpecialClass.h"
@interface FOOMySpecialClass()
@property (nonatomic, readwrite, assign) BOOL isFoo;
@end
@implementation FOOMySpecialClass
- (void)setIsFoo:(BOOL)isFoo {
_isFoo = isFoo; // <-- Change here and no crash
}
@end
// main.m
#import <Foundation/Foundation.h>
#import "FOOMySpecialClass.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
FOOMySpecialClass *mySpecialClass = [[FOOMySpecialClass alloc] init];
[mySpecialClass setIsFoo:YES];
NSLog(@"%@", mySpecialClass.isFoo ? @"YES" : @"NO"); // <-- boom.
}
return 0;
}