Problem
I am migrating some legacy code (pre iOS 5) where I lazy load some readonly
properties. I want to update this code to iOS 5+ with ARC. But I just learning about ARC.
.h
@property (nonatomic, retain, readonly) NSDateFormatter *timeFormatter;
.m
- (NSDateFormatter *)timeFormatter {
if (timeFormatter == nil) {
timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"h:mm a"];
}
return timeFormatter;
}
What I tried
I have tried to simply update my code, but receive an: Assignment to readonly property.
.h
@property (nonatomic, strong, readonly) NSDateFormatter *timeFormatter;
.m
- (NSDateFormatter *)timeFormatter {
if (self.timeFormatter == nil) {
self.timeFormatter = [[NSDateFormatter alloc] init];
[self.timeFormatter setDateFormat:@"h:mm a"];
}
return self.timeFormatter;
}
I also reviewed:
- ios ARC strong and alloc
- Thread safe lazy initialization on iOS
- http://www.cocoanetics.com/2012/02/threadsafe-lazy-property-initialization/
Question
What is the correct way to lazy-load a readonly
property in iOS 5+ with ARC? Would appreciate code samples for both .h and .m.