类方法和“在线分配的对象的潜在泄漏...”
我遇到这种情况:
- (void) foo {
NSLog(@"Print this: %@", [MyObject classString]);
}
// So in MyObject.m I do
@implementation MyObject
+ (NSString *) classString {
return [OtherObject otherClassString]; //The Warning "Potential leak..." is for this line
}
@end
// Finally in OtherObject
@implementation OtherObject
+ (NSString *) otherClassString {
NSString *result = [[NSString alloc] initWithString:@"Hello World"];
return result;
}
@end
一开始,我对 otherClassString
和 classString
发出警告,但通过这种方式 otherClassString
这项工作。
现在我的问题出在 MyObject
的 classString
中。我尝试了很多方法,但总是显示此警告。我不能在类方法中调用类方法吗?
I have this situation:
- (void) foo {
NSLog(@"Print this: %@", [MyObject classString]);
}
// So in MyObject.m I do
@implementation MyObject
+ (NSString *) classString {
return [OtherObject otherClassString]; //The Warning "Potential leak..." is for this line
}
@end
// Finally in OtherObject
@implementation OtherObject
+ (NSString *) otherClassString {
NSString *result = [[NSString alloc] initWithString:@"Hello World"];
return result;
}
@end
In the beginning, I had a warning for otherClassString
and for classString
but with this way for otherClassString
this work.
Now my problem is in classString
in the MyObject
. I tried a lot of things, but this warning is always shown. Can't I call a class method inside a class method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
+otherClassString
创建一个保留计数为 1 的对象并返回它。这也用作+classString
的返回值。如果您的方法不是以
init
、new
或copy
开头,则应返回自动释放的对象。在任何使用您的(按原样)的地方,它们都应该返回一个自动释放的对象。Your
+otherClassString
creates an object with retain count 1 and returns it. This is used as return value for+classString
as well.If your methods don't begin with
init
,new
, orcopy
, you should return autoreleased objects. Everywhere where yours (as is) are used, they'll be expected to return an autoreleased object.您的问题归结为:您有一个方法,根据命名约定,该方法应该返回自动释放的对象,但它返回保留的对象。该方法是
+otherClassString
。将其更改为以下内容:Your problem boils down to this: You have a method which, by the naming conventions, should be returning an autoreleased object but instead it's returning a retained object. That method is
+otherClassString
. Change it to the following:我已经准确地重现了您的场景,没有发生错误或警告。也许您的头文件有问题。这是我的代码(Xcode 4.2 和 iOS5):
I have reproduced your scenario exactly and no errors or warnings occurs. Maybe you have an issue on your header files. Here’s my code (Xcode 4.2 and iOS5):