开发者

Memory leak on allocating and releasing an NSArray

I'm getting a reported memory leak from Instruments on the following code:

    NSArray *array = [[NSArray alloc] initWithObjects:@"Amount (oz):", @"Amount (ml):", @"Supplement:", nil];
self.fieldLabels = array;
[array release];

fieldLabels is an iVar, declared as:

 NSArray *fieldLabels;
@property (nonatomic, retain) NSArray *fieldLabels;

Instruments reports the following:

#   Category    Event Type  Timestamp   RefCt   Address Size    Responsible Library Responsible Caller
0   __NSArrayI  Malloc  00:16.513.592   1   0x660bb40   32  InfantCare  -[Supplemental_Amount viewDidLoad]
1   __NSArrayI  Retain  00:16.513.595   2   0x660bb40   0   InfantCare  -[Supplemental_Amount setFieldLabels:]
2   __NSArrayI  Release 00:16.513.595   1   0x660bb40   0   InfantCare  -[Supplemental_Amount viewDidLoad]

I then changed the code开发者_StackOverflow社区 so instead of:

self.fieldLabels = array;

I put:

[self setFieldLabels:array];

No more leak (supposedly!). Why would this be? Thanks!


Both syntax are identical. Given the fact that you have declared your fieldLabels property with a retain attribute the reference count of your array after your call to setFieldLabels (which is called when you write: self.fieldLabels = array) is 1 which is what you would expect. Indeed given the sequence of calls in your code the following is happening:

  1. NSArray *array = [[NSArray alloc] initWithObjects:@"Amount (oz):", @"Amount (ml):", @"Supplement:", nil]; This sets the refCount of the memory allocated to 1
  2. self.fieldLabels = array; Will retain the array, release whatever was previously retained by fieldLabels and assign fieldLabels to the retained array. At this stage the retain count of array is 2 (1 from init, 1 from the property assignment).
  3. [array release]; Brings the retain count back to 1 for the array which is what you want.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜