2

私は何が起こっているのかを知るために数日を費やしました. 私は大量のメモリ管理ドキュメントを読みましたが、「リリースが必要なすべての割り当てについて」と聞いてうんざりしています-それは知っていますが、コードがメモリリークを生成している理由をまだ理解できません。

プロパティの 1 つとして NSMutableDictionary を持つ単純なカスタム クラスを作成しています。基本的に、XMLELement を模倣します。私は一生、辞書の割り当てがメモリリークを引き起こしている理由を理解できません。リークはデバイスとシミュレータで発生します - デバイスで 5 リーク、シミュレータで 20 リーク。

変数 *tmp を宣言して割り当てると、リークが発生します。
属性の詳細 (名前と値) を設定すると、リークもあります。

これは私を夢中にさせています。助けてください!

コードの一部:

@interface IMXMLElement : NSObject {

NSString *strElementName;
NSString *strElementValue;
NSMutableDictionary *dictAttributes;
}

@property (nonatomic, retain) NSString *strElementName;
@property (nonatomic, retain) NSString *strElementValue;
@property (nonatomic, retain) NSMutableDictionary *dictAttributes;

@end

@implementation IMXMLElement

@synthesize strElementName;  
@synthesize strElementValue;  
@synthesize dictAttributes;

-(id)initWithName:(NSString *)pstrName
{
    self = [super init];

    if (self != nil)
    {
        self.strElementName = pstrName;
        **LEAK NSMutableDictionary *tmp = [[NSMutableDictionary alloc] init];
        self.dictAttributes = tmp;
        [tmp release];
    }

    return self;
}

-(void)setAttributeWithName:(NSString *)pstrAttributeName  
andValue:(NSString *)pstrAttributeValue  
{  
    **LEAK [self.dictAttributes setObject:pstrAttributeValue forKey:pstrAttributeName];  
}

-(void)dealloc
{
    [strElementName release];
    [strElementValue release];
    [dictAttributes release];
    [super dealloc];    
}

次のコードを使用してこのクラスにアクセスします。

NSString *strValue = [[NSString alloc] initWithFormat:@"Test Value"];

IMXMLElement *xmlElement = [[IMXMLElement alloc] initWithName:@"Test_Element"];
[xmlElement setAttributeWithName:@"id" andValue:strValue];

4

3 に答える 3

0

プロパティとして文字列がある場合、それらを保持ではなくコピーとして宣言します。

  NSMutableDictionary *tmp = [[NSMutableDictionary alloc] init];
  self.dictAttributes = tmp;
  [tmp release];

上記は不要ですが、代わりに次のようにしてください:( この自動解放オブジェクトの保持カウントは自動的にインクリメントされます)

self.dictAttributes = [NSMutableDictionary dictionaryWithCapacity:0];

Deallocで行う:( 保持カウントは自動的にデクリメントされます)

self.dictAttributes = nil;

通常、プロパティの場合、get / setterがそれを処理するため、明示的に解放するのではなく、nilに設定するだけです。

于 2010-09-02T03:31:24.343 に答える
0

典型的な構文はNSMutableDictionary *tmp = [[[NSMutableDictionary alloc] init] autorelease];

于 2010-09-02T03:08:03.953 に答える
0

dictAttributes を解放する前に [dictAttributes removeAllObjects] を試してください。

編集:

また、「tmp」にメモリを割り当てているため、正の割り当てになります。dictAttributes からの参照があるため、メモリは保持されます。

次に、ディクショナリに要素を追加すると、より積極的な割り当てが行われます。これも割り当てる必要があり、ディクショナリの内部参照によってメモリに保持されます。

于 2010-09-02T02:55:50.290 に答える