views:

89

answers:

1

Just a simple question on NSStrings, I have a piece of code that assigns a value to a string, depending on what is found it is either assigned a value by substringToIndex or the constant string @"0.00", is it okay to use

// Save if value found, otherwise set to 0.00
if (parsedCharacters == nil || [parsedCharacters isEqualToString:@""])
        self.currentDiscountedPrice = @"0.00";
else
{
  // Truncate extra digits from string to 2 decimal places (find full stop, save 2 places after it)
  NSRange fullStopRange = [parsedCharacters rangeOfString:@"."];
  self.currentDiscountedPrice = [parsedCharacters substringToIndex:(fullStopRange.location + 3)];
}

for the assignment since it will release the old value & retain the new value?

There is no way of knowing whether the var was assigned the constant string or the substringToIndex returned value in the previous iteration but I was told calling retain & release on constant strings is harmless, is this true?

+1  A: 

NSString is not special; all Cocoa objects follow the Cocoa memory-management rules. As long as you do, too, you'll be fine.

I was told calling retain & release on constant strings is harmless, is this true?

Yes. You should treat them the same as any other string you don't own: Retain it if you want to own it, or make a copy and own that; then be sure to release what you own.

… should I rather explicitly release the old value & retain the substringToIndex value or it okay to just use self.currentDiscountedPrice = for both assignments?

You should use the property everywhere but in init methods and dealloc. Those are the only methods that should explicitly send retain and release messages to the object in the instance variable.

The reason for both sides of that paragraph is that you, or a subclass, may implement custom accessors for the property. The custom behavior may be dangerous to have run on a half-inited or half-deallocked object, but you'll probably want it everywhere else.

There is no harm in passing a constant-string object to a property setter. It will retain or copy the object as normal.

On that note, when a property's value is an object of a class with a mutable variant (as NSString has NSMutableString), you should declare the property as copying its value (@property(copy) or @property(nonatomic, copy)), in order that you do not take co-ownership of someone else's mutable object. If they mutate the object, this could cause problems for you, particularly if you stored the object in a hashing collection (such as as a dictionary key) rather than in an instance variable.

Peter Hosey
Thank you Peter.
Spider-Paddy