保留周期和弱势财产

时间:2017-05-04 09:53:46

标签: objective-c

我有3个课程:function myFunction(){ var tableStr = `<table id="myTable"> <tr class="header"></tr> <tr><td>Germany</td></tr> <tr><td>Sweden</td></tr> <tr><td>UK</td></tr> <tr><td>Germany</td></tr> <tr><td>Canada</td></tr> <tr><td>Italy</td></tr> <tr><td>UK</td></tr> <tr><td>France</td></tr> </table>`; document.getElementById('tableContainer').insertAdjacentHTML('beforeend', tableStr) } CoreCache

HttpClient中,我使用参数Core初始化缓存,然后将core实例传递给Cache

Core.m

HttpClient

Cache.m

-(id)init {
    self = [super init]; 
    MyCache *cache = [[MyCache alloc] initWithCore:self];
    self.httpClient = [[MyHttpClient alloc] initWithCache:cache];
}

MyHttpClient.m

@interface MyCache ()
  @property (nonatomic, strong) MyHttpClient *httpClient;
@end

@interface Core ()

@property (nonatomic, strong) MyHttpClient *httpClient;

@end

@implementation MyCache
  -(instancetype) initWithCore: (Core *)core
  {
    if (self = [self init]) {
        self.httpClient = core.httpClient;
    }
    return self;
  }
@end

-(void)foo
{
  [self.httpClient doSomething];
}

您可以看到,@interface MyHttpClient : NSObject @property (nonatomic, strong) MyCache *cache; -(instancetype) initWithCache: (MyCache *)cache; @end @implementation MyHttpClient -(instancetype) initWithCache: (MyCache *)cache { if (self = [self init]) { self.cache = cache; } return self; } -(void) doSomething { [self.cache cacheSomething]; } 通过依赖注入使用MyCache实例,而另一方面MyHttpClient实例使用MyHttpClient实例。

这是否称为保留周期?

我是否需要将MyCacheMyCache属性设为

感谢,

1 个答案:

答案 0 :(得分:6)

如果将逻辑放入一个简单的图表中。您可以看到HttpClient和Cache之间存在保留周期。我认为最好将Cache中的httpclient属性设置为weak来解决保留周期。

Diagram