B.Moahmmed.Amine
B.Moahmmed.Amine

Reputation: 11

Where is the leaks here?

if ([elementName isEqualToString:@"type"])
    {
        items       = [[NSMutableDictionary alloc] init];
        currentname = [[NSMutableString alloc] init];
        currentid   = [[NSMutableString alloc] init];
    }

how can resolv leaks problem

Upvotes: 0

Views: 106

Answers (3)

Hailei
Hailei

Reputation: 42163

  • currentElement = [elementName copy];
  • items = [[NSMutableDictionary alloc] init];
  • currentname = [[NSMutableString alloc] init];
  • currentid = [[NSMutableString alloc] init];

These all cause memory leak if the method parser:didStartElement:namespaceURI:qualifiedName:attributes: runs more than once.

An easy way to fix this issue is to change your variables to properties. For example, in your header file, change:

@interface SomeClass {
    NSMutableDictionary *items;
}

to:

@interface SomeClass {
}

@property (retain) NSMutableDictionary *items;

And add this after @implementation SomeClass:

@synthesize items;

Then change your original code to:

self.items = [[[NSMutableDictionary alloc] init] autorelease];

Both "Analyze" feature in Xcode and Instruments are your friend when you want to check memory issues.

Upvotes: 1

Kemenaran
Kemenaran

Reputation: 1431

If you know for sure that there is a leak in this snippet, I assume you already ran Instruments, which told you that the NSString object "elementName" was leaking.

Romain is right: a good step is to run the Xcode Static Analyzer. It will probably tell you that [elementName copy] returns an object with a retain count of +1. (Per Cocoa conventions, all "copy" selectors transfer the ownership of the returned object to your code).

So the solution here is to balance the "copy" call by releasing the copied object when you don't need it, using:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{ 
     [currentElement release];
     currentElement = [elementName copy];

     // your method body here…
 }

Upvotes: 0

Arcank
Arcank

Reputation: 456

currentElement = [elementName copy];
items          = [[NSMutableDictionary alloc] init];
currentname    = [[NSMutableString alloc] init];
currentid      = [[NSMutableString alloc] init];

You leak previous value stored in these ivars.

Upvotes: 2

Related Questions