gpt4 book ai didi

objective-c - 类方法和 "Potential leak of an object allocated on line..."

转载 作者:行者123 更新时间:2023-12-02 07:09:05 26 4
gpt4 key购买 nike

我有这种情况:

- (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

一开始,我收到了针对 otherClassStringclassString 的警告,但通过这种方式,otherClassString 可以正常工作。

现在我的问题出在 MyObject 中的 classString 中。我尝试了很多东西,但总是显示此警告。我不能在类方法中调用类方法吗?

最佳答案

您的 +otherClassString 创建了一个保留计数为 1 的对象并将其返回。这也用作 +classString 的返回值。

如果您的方法不是以initnewcopy 开头,您应该返回自动释放的对象。在使用你的(原样)的任何地方,他们都应该返回一个自动释放的对象。

+ (NSString *) otherClassString {
NSString *result = [[[NSString alloc]
initWithString:@"Hello World"]
autorelease];
return result;
}

关于objective-c - 类方法和 "Potential leak of an object allocated on line...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7883331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com