我想了解下面的代碼有什麼問題。這個init方法有什麼問題會導致內存問題? (iOS)
想象一下下面的類,「富」:
@protocol FooDelegate <NSObject>
- (void)hereTakeThisFooBarDic:(NSDictionary *)fooBarDic;
@end
@interface Foo : NSObject <BarDelegate>
@property (nonatomic, strong) Bar *bar;
@property (nonatomic, weak) id <FooDelegate> *fooDelegate;
- (void)getFooBarDicForNum:(int)fooBarNum;
@end
@implementation Foo
static Foo *foo = nil;
- (id)init {
if (!foo) {
foo = [super init];
self.bar = [[bar alloc] init];
}
return foo;
}
- (void)getFooBarDicForNum:(int)fooBarNum {
self.bar.fooDelegate = self;
[self.bar getFooBarDicFromIntarwebsNumber:fooBarNum];
}
//We get this callback from self.bar after a few ms
- (void)callbackWithFooBarDicFromIntarwebs:(NSDictionary *)fooBarDic {
[self.fooDelegate hereTakeThisFooBarDic:fooBarDic];
}
@end
我們在代碼中調用美孚從什麼地方是這樣的:
for(int i=0; i < 10; i++) {
Foo *foo = [[Foo alloc] init];
[foo getFooBarDicForNum:i];
}
然後我們得到的hereTakeThisFooBarDic
方法回調後。
但問題是我們正在獲得無限的內存增長。看來Foo的init
方法就像一個singleton,但每次我們稱它爲它分配更多的內存。它雖然沒有註冊爲內存泄漏。儘管如此,在查看這段代碼時,它看起來並不像做單身人士的正確方式。
我想知道這段代碼的作者做錯了什麼。
永遠不要使委託屬性'strong'。它應該是'弱'。 – rmaddy
對不起,這只是一個錯字。 – CommaToast
永遠不要使用'get'開始一個方法名(除非它屬於各種罕見的Objective-C慣例之一,在這個慣例中它是有道理的,但這不是)。 – bbum