Do you need to provide your Objective-C class with a read-only computed property ? Not a big task… just define the property in the .h file as usually, remembering to specify “readonly” among the attributes. In the .m implementation file you won’t use the @synthesize keyword to automatically generate the getter and the setter methods of the property as you probably usually do. Instead you’ll write the getter method. This allows you to write the code to compute the property.
Here’s an example, don’t take it as an example of good programming, it’s only to demonstrate the use of read-only computed properties.
The Booking class has a date property. This is awkwardly not a NSDate, but a NSString. This is because the date is actually loaded from an XML service and the original programmer choose to store it as a NSString. Thus, we’d like to have a nice NSDate property, standing by the NSString property. Here the fact is that we cannot add another NSDate property in the standard way, to avoid the two dates be unrelated. What we really need is that the NSDate property would be computed from the string version of the date. Thus, we need a property whose value is computed starting from the value of another property and not stored in an instance variable as we’re used to do.
So, here’s the code… first of all the .h file
#import <Foundation/Foundation.h>
@interface Booking : NSObject {
NSString *date;
}
@property(nonatomic,retain) NSString *date;
@property(nonatomic,readonly) NSDate *nsDate;
@end
As you can see, we declared the read-only property “nsDate” but there is no any instance variable to store it. Let’s go ahead with the .m implementation file.
#import "Booking.h"
#import "Conversion.h"
@implementation Booking
@synthesize date;
-(NSDate*)nsDate{
//Here an utility method is used to convert the date from NSString to NSDate.
return [Conversion toNSDate:date];
}
@end
So, here’s the trick. Just write the code that computes the value of the property in the getter method.