• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Re Re: String variables in classes
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Re Re: String variables in classes


  • Subject: Re: Re Re: String variables in classes
  • From: Charles Srstka <email@hidden>
  • Date: Sun, 2 Jan 2011 17:32:35 -0600

On Jan 2, 2011, at 5:17 PM, Brian Durocher wrote:

> - (void) setCaption: (NSString*)input
> {
>    [caption autorelease];
>    caption = [input retain];
> }

For this (and for the rest of the NSString ivars), it’s generally better to use -copy rather than -retain. The reason for this is that it is perfectly valid to pass an NSMutableString to this method, since it is a subclass of NSString. If a caller gave you a mutable string and then changed it later, it could have unpredictable results for your object. Using -copy makes sure you have your own immutable copy of the string which can’t be changed (and as an optimization, if the string is already immutable, -copy just retains it, so it’s just as efficient).

> - (void) combineString: (NSString*) input1 : (NSString*) input2
> {
>    [temp autorelease];
>    temp = @"";
>    temp = [[temp stringByAppendingFormat:@" %@ %@ \n", input1, input2]
> retain];
> }

The autorelease is fine in terms of not causing memory leaks, but why are you assigning an empty string to temp immediately before you assign something else to it? That’s an unnecessary line of code. Actually, there’s a lot of unnecessary code here — why not just use the accessor method to set the string?

- (void) combineString: (NSString*) input1 : (NSString*) input2
{
   [self setTempString:[[self temp] stringByAppendingFormat:@" %@ %@ \n", input1, input2]];
}

In general, it’s a good idea to cut down on the direct use of ivars and use accessors as much as possible. This will make your design more flexible should you decide to change the underpinnings of something in the future.

Charles_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden

References: 
 >Re Re: String variables in classes (From: Brian Durocher <email@hidden>)

  • Prev by Date: Re Re: String variables in classes
  • Next by Date: Re: Search within a UIWebView (iOS 4.2)
  • Previous by thread: Re Re: String variables in classes
  • Next by thread: Re: Re Re: String variables in classes
  • Index(es):
    • Date
    • Thread