I’ve got a class with two properties:
@interface Contact : NSObject {
NSString *lastname;
NSString *lastNameUpper;
}
I’ve declared lastname as a property (and synthesize it in the .m-file):
@property (nonatomic, retain) NSString *lastname;
However, I want to write my own method to access the lastNameUpper, so I declared a method:
- (NSString *) lastNameUpper;
and implemented it like this:
- (NSString *) lastNameUpper {
if (!lastNameUpper) {
lastNameUpper = [lastname uppercaseString];
}
return lastNameUpper;
}
This works all right, but as this is called quite often, a lot of temporary objects are called. Interestingly, the Instruments show a lot of “Malloc (4k)”, and the number increase each time lastNameUpper is accessed. I can also see that the memory is allocated in objc_retailAutoreleaseReturnValue.
As this was working fine before I converted my project to ARC, I’m assuming that I have to make some ARC specific additions to the method signature, but I can’t seem to be able to make it work.
Any suggestions?
Override the
- (void)setLastname:(NSString*)aLastnamemethod (created automatically by@synthesize lastname, and set lastNameUpper as in the existing method.Now create a lastNameUpper property (and synthesize it):
Since this will return the pointer of the lastNameUpper instance variable, no copies should be made whenever this is accessed.