未调用ios Singleton Pattern和完成处理程序

时间:2014-04-02 03:05:42

标签: ios singleton

所以我有一个WebImage类,它保存图像和图像URL。我有一个ImageLoader类,它只能有一个实例。它拥有一个可变的WebImages数组,基本上只加载所有图像。但由于某种原因,从队列中抓取项目并加载其图像的递归方法在加载一个图像后停止,有时在之前。我怀疑它与单例模式有关,并且对象以某种方式过早地释放了某些东西。一些代码:

我的ImageLoader类:

@property (strong, nonatomic) ConnectionManager *conman;
@property (strong, nonatomic) NSMutableArray *queue;
@end
...
+(ImageLoader*)defaultLoader{
    static dispatch_once_t pred;
    static ImageLoader *sharedInstance = nil;
    dispatch_once(&pred, ^{
        sharedInstance = [[ImageLoader alloc] init];
    });
    return sharedInstance;
}

-(id)init{
    self = [super init];
    self.queue = [[NSMutableArray alloc] init];
    self.conman = [[ConnectionManager alloc] init]; //a manager for loading images and whatnot.
    return self;
}

-(void)addToQueue:(WebImage*)webimage{
    [self.queue addObject:webimage];
    if (!fetching){ //if this method is already running then just let it keep going
        [self loadImages];
    }
}
-(void)loadImages{
    fetching = YES;
    if (self.queue.count == 0){ //base case
        fetching = NO;
        return;
    }
    WebImage *webimage = [self.queue firstObject];
    [self.queue removeObject:webimage]; //move closer to the base case
    [self.conman getImageWithURL:webimage.image_URL inBackgroundWithBlock:^(NSString *error, id image) {
        if (image){
            webimage.image = image;
        }else{
            NSLog(@"error getting image %@, error: %@", webimage.image_URL, error);
            [self.queue addObject:webimage]; //add it to the end of the queue to try again later
        }
        [self loadImages];
    }];
}

在其他课程中我只是打电话:

[[ImageLoader defaultLoader] addToQueue:webImage];

编辑: 肯定会发布一些东西。我不知道问题是什么,但我更改了defaultLoader方法,只返回一个指向appdelegate所持有的实例的指针来修复问题。虽然我仍然想理解为什么我上面的东西不起作用。

+(ImageLoader*)defaultLoader{
    ImageLoader *loader = ((AppDelegate*)[UIApplication sharedApplication].delegate).imageLoader;
    if (!loader) loader = [[ImageLoader alloc] init];
    return loader;
  /*  
    static dispatch_once_t prede;
    static ImageLoader *sharedInstance = nil;
    dispatch_once(&prede, ^{
        sharedInstance = [[ImageLoader alloc] init];
    });
    return sharedInstance;
   */
}

0 个答案:

没有答案