开发者

objective c - Warning "Potential leak of an object" created with a class method

I am using XCode 4.0.2 for a iOS4 project.

I have this class method that construct an object. This is a constant that i need occasionally from start to end of the app.

objective c - Warning "Potential leak of an object" created with a class method

However, ru开发者_JAVA百科nning the Analyze tool this gives me a "Potential leak of an object" warning for the c object.

Should I be concerned? How can I fix it?

Thank you


You should read the Memory Management Programming Guide provided by Apple.

You should prefix your method name (+[XYZ A] in this instance) with new to make it clear that callers of your method know that they are responsible for releasing the object they receive. You would rename the method to +[XYZ newA].

If you do not wish to rename your method, you should at least return an autoreleased object, e.g. change the last line to return [c autorelease];


Every time you use that method, it creates a new instance of XYZ through the (deprecated) +new method.

If you want a single object of class XYZ that persists to the end of the app, you'll need to make some changes. The simplest way is to create this object on class initialization. In the .m file for whatever class we're looking at here, add the following:

static XYZ *instance = nil;

+ (void)initialize {
    if (self != [ThisClass class])
        return;

    instance = [[XYZ alloc] init];
    instance.X = ...;
    instance.Y = ...;
    instance.Z = ...;
}

And then, your A method:

+ (XYZ *)A {
    return instance;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜