Search code examples
accessorobjective-c-2.0

NSMutableString and setting up accessor methods Objective-C 2.0


There is a copy attribute for synthesised accessor methods ex:

@property (copy) NSMutableString *string;

When assign using this setter method it seems to always call the copy method, even though I would like to create a mutable copy of what ever I assign to string, during assignment of the instance variable string.

Is this a know issue and are there any workarounds?

Thanks :-)


Solution

  • Don't call @synthesize string in your .m implementation file and instead write your own getter.

    e.g.

    - (NSMutableString *) string
    {
        NSMutableString * stringToReturn = [NSMutableString stringWithString: someStringObject];
    }
    

    More information about properties (and what to do when you don't do @synthesize) can be found at:

    http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html

    p.s. the property name "string" may be confusing to anyone else who looks at your code down the road... I'd recommend changing that to be more program-specific