ofirbt
ofirbt

Reputation: 1896

Should I release @property (nonatomic, copy)?

I'm using UISearchBar, and one of its properties, text, is declared as follows:

Abstract: The current or starting search text.
Declaration: @property(nonatomic, copy) NSString *text;

I know that the rule is to release what ever you use +alloc, +new or -copy.

I did:

NSString *searchText = searchBar.text;

And:

[searchText release];

And I got a nice EXC_BAD_ACCESS message. When I removed the release line, the EXC_BAD_ACCESS message stopped to appear, so I assumed that it is the eror source.

The question: Shouldn't I release searchText, since it comes from a property that uses copy?

Upvotes: 0

Views: 1571

Answers (3)

James Bedford
James Bedford

Reputation: 28982

The copy attribute of the property means that the object is copied before assigning to the instance variable. When you access this property you then get a reference to the copy that was made.

When you set the the text on the searchbar:

NSString* myTextString =  [[NSString alloc] initWithString:@"My Text String"];
mySearchBar.text = myTextString;
[myTextString release];

Upvotes: 2

Mr. Berna
Mr. Berna

Reputation: 10655

To elaborate on Rob Napier's correct answer:

NSString *searchText = searchBar.text;

This code assigns a reference to the text property of searchBar to searchText. This is not a copy of the searchText, just another reference to the same NSString object in the searchBar object. Releasing searchText is the same as releasing searchBar.text, which cause your EXC_BAD_ACCESS message.

In this declaration of the text property, the getter method is merely:

- (NSString *)text {
   return text;
}

The more interesting method is the setter method. For this declaration, the setter is similar to:

- (Void)setText:(NSString *)newString {
  if (text != newString) {
    [text release];
    text = [newString copy];
  }
}

Upvotes: 1

Rob Napier
Rob Napier

Reputation: 299633

No, you should not use release here. The "copy" in this case refers to how the setter is implemented, not the getter. The call you made (-text) does not include the word "copy" so you should not release the result.

Upvotes: 8

Related Questions