开发者

Iphone Right way to set a property

i have the following code in .h:

@property (nonatomic, retain) NSArray *a开发者_如何转开发rrayData;

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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜