0

I'm getting a leak memory error with a custom object (called LinesOfText class) returned by a function. This is a simple example with no detailed implementation:

-(void)myMethod(){
LinesOfText *linesOfText = [self linesOftext:@"this is my text"];
} 

-(LinesOfText *)linesOftext:(NSString *)_string{
LinesOfText *linesOfText = [[linesOfText alloc] init];
[linesOfText propsOfTextLine:_string];
return linesOfText;
}

I'm not sure where I've to release the object

4

2 回答 2

0

In myMethod, use:

LinesOfText *linesOfText = [[LinesOfText linesOftext:@"this is my text"] autorelease];

Instead of:

LinesOfText *linesOfText = [self linesOftext:@"this is my text"];

In your other file, use:

+(LinesOfText *)linesOftext:(NSString *)_string {

Instead of:

-(LinesOfText *)linesOftext:(NSString *)_string {
于 2012-10-08T22:31:07.877 回答
0

Usually such methods should return an autoreleased value, that is, in your linesOftext method, do

return [linesOfText autorelease];

(or call autorelease on it right when creating it),

LinesOfText *linesOfText = [[[linesOfText alloc] init] autorelease];

By convention, if your method name contains "new", "alloc", "copy", it should return a retained object. Return an autoreleased object otherwise (e.g. see methods like NSMutableArray's arrayWithCapacity:, or NSString's stringWithFormat:... See this for more information: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html

And yes, like zsnow suggests it may be a good idea to make it a static (+) method if possible.

于 2012-10-08T22:33:34.040 回答