2011-03-22 112 views
0
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
    namespaceURI:(NSString *)namespaceURI 
qualifiedName:(NSString *)qName 
    attributes:(NSDictionary *)attributeDict{ 

    //currentElenet is NSString 
    currentElement = [elementName copy]; 

    if ([elementName isEqualToString:@"struct"]) {  

     self.post = [[Question alloc] init]; 

    } 
} 

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ 

    if ([currentElement isEqualToString:@"string"]) { 
     post.text = [NSString stringWithFormat:@"%@ %@", post.text, string]; 
    } 
} 

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI 
qualifiedName:(NSString *)qName{ 

    if ([elementName isEqualToString:@"struct"]) { 

     [conversations addObject:post]; 
     [post release]; 
     post = nil; 
    } 
} 

//Question.m file 
@synthesize text 

-(id)init{ 

    self = [super init]; 
    if (self == nil) { 

    } 
    else { 
      //declared as retain in .h file 
     text = [[NSString alloc]initWithString:@""]; 
    } 
    return self; 
} 

-(void)dealloc{ 
    [super dealloc]; 
    [title release]; 
} 

你們看到有什麼記憶在這裏泄漏嗎?我調用NSXML委託方法,它基本上把一個「問題」的實例放入NSMutableArray中。我檢查過儀器,解析它時發現內存泄漏。但我不明白爲什麼...目標C,內存泄漏?

回答

2

currentElement = [elementName copy];

請在文檔中讀取copy API的描述。這裏要提到的是

this method retains the new object before returning it. The invoker of the method, however, is responsible for releasing the returned object.

0

currentElement ---是不是在你的解析流得到釋放......代碼的其餘部分看起來是正確的

1

你真的需要包括你的財產申報,以便人回答有保證內存管理問題(因爲屬性定義內存的管理方式),但假設所有retain屬性:

  • currentElement從不被釋放ppears

  • text似乎永遠被釋放

  • self.post分配的[[Question alloc] init]結果。該方法的結果已經是您擁有的一個對象,並且設置者再次保留該對象。它應該在方法退出之前發佈,沿着線:

    id question = [[Question alloc] init]; 
    self.post = question; 
    [question release]; 
    

    (還應該在dealloc釋放或當你用它做平衡的setter)