当前位置: 动力学知识库 > 问答 > 编程问答 >

memory management - Iphone Right way to set a property

问题描述:

i have the following code in .h:

@property (nonatomic, retain) NSArray *arrayData;

And in the .m in method initWithNibName:

self.arrayData = [NSArray arrayWithObjects:@"Usuario:",@"Password:",nil];

is it right in order to call

[self.arrayData release]

safely in order to release the object?

网友答案:

No, it is not correct to call release on your property. The problem with it is, that you release your property, it will get deallocated, but you didn't set your pointer to nil, so somebody might send a message to your property and get a crash.

What you can do is the following:

  1. self.arrayData = nil; ( which will release the previous saved instance, and set the property to nil)
  2. [arrayData release]; arrayData = nil; (here you are accessing your ivar instead of your property; setting your ivar to nil is a precaution)
  3. [self->arrayData release]; self->arrayData = nil (this is exactly the same as #2)

Hope this helps.

网友答案:

You need to call:

[arrayData release]

Calling [self.arrayData release]; will not have the effect you want it to in either case.

If you're wondering why this is, check this question out: difference between [self.property release] and [property release]

网友答案:

A) it is a bad idea to do this in your initializer (e.g., initWithNibName:bundle:)

self.arrayData = [NSArray arrayWithObjects:@"Usuario:",@"Password:",nil];

use this instead:

arrayData = [[NSArray alloc] initWithObjects:@"Usuario:",@"Password:",nil];

you should not call these accessors (properties) in initializers or dealloc.

B)

is it right in order to call

[self.arrayData release]

no. in many cases (assuming you implement some of the properties you've declared), you may not be returned the the ivar. you may receive a copy, a placeholder object, or a subclass may have chosen to re-implement the accessors (as some examples). in these cases, it's easy to over-release or over-retain (resulting in evil stuff, like leaks and crashes).

this is typical:

self.arrayData = nil;

unless you are in dealloc of the object which declared the ivar:

- (void)dealloc {
  [arrayData release], arrayData = nil;
  [super dealloc];
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: