Objective C alloc/release error

后端 未结 4 1848
庸人自扰
庸人自扰 2020-12-07 06:19

I have the following problem:

in header;

GDataXMLDocument *doc;
NSString *xmlBody;
@property (nonatomic,copy) NSString *xmlBody;
@property (nonatomic         


        
相关标签:
4条回答
  • 2020-12-07 06:51
    NSData *xmlData = doc.XMLData;
    newXML = [[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length] 
    encoding:NSUTF8StringEncoding];
    

    What is your newXML? is it a ivar and synthesize it and retain it? if yes the compiler will automatically generate getter and setter methods.

    NSData *xmlData = doc.XMLData;
    self.newXML = [[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length] 
    encoding:NSUTF8StringEncoding];
    self.timestamp = nil;
    

    If its not property then

    NSString* newXML = [[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length] 
    encoding:NSUTF8StringEncoding];   
    self.xmlBody=newXML;   
    [newXML release]; 
    
    0 讨论(0)
  • 2020-12-07 06:56

    One "problem" with singleton objects is that they appear to leak. If you create an object and never destroy it, Instruments says it's a leak, even if your intention was never to release it.

    0 讨论(0)
  • 2020-12-07 06:58

    This looks wrong:

    [doc release];
    

    Why are you releasing an object managed by a property?

    In your @synthesize statements change them to:

    @synthesize doc = doc_;
    @synthesize xmlBody = xmlBody_;
    

    Then fix all the resulting errors to go through the property, releasing the properties ONLY in dealloc.

    Edit:

    You say it crashes releasing theXML. This code is wrong:

    NSString *theXML = [[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length] encoding:NSUTF8StringEncoding];  
            theXML =[theXML stringByReplacingOccurrencesOfString:@"inferenceresponse" withString:@"inferencerequest"];
    [theXML release];
    

    You alloc a string, replace that variable with the "stringByReplacing..." call with a string that is autoreleased, then try to release the resulting string that is autoreleased which will crash. When you don't need to keep a string around after the method you are in, ALWAYS use autorelease. The correct code is:

     NSString *theXML = [[[NSString alloc] initWithBytes:[xmlData bytes] length:[xmlData length] encoding:NSUTF8StringEncoding] autorelease];  
                theXML =[theXML stringByReplacingOccurrencesOfString:@"inferenceresponse" withString:@"inferencerequest"];
    

    And take out [theXML release] - there will be no leak.

    I think you should really switch to using ARC as soon as you possibly can... it will save you from a lot of such misunderstandings.

    0 讨论(0)
  • 2020-12-07 07:01

    If you want to release an ivar/property(retain), this is not how to to it:

    [self.doc release];
    

    instead:

    self.doc = nil;
    
    0 讨论(0)
提交回复
热议问题