Skip to content

Instantly share code, notes, and snippets.

@petermolnar-dev
Created January 5, 2017 20:36
Show Gist options
  • Save petermolnar-dev/33ffc6758f5497fa22eeb63cefbcf481 to your computer and use it in GitHub Desktop.
Save petermolnar-dev/33ffc6758f5497fa22eeb63cefbcf481 to your computer and use it in GitHub Desktop.
PMOPictureController.m - With delegation
#import "PMOPictureController.h"
#import "PMODownloader.h"
#import "PMOPictureWithURL.h"
#import "PMODownloadNotifications.h"
@interface PMOPictureController()
/**
Our private data class, storing and hiding the information.
*/
@property (strong, nonatomic, nullable) PMOPictureWithURL *pictureWithUrl;
@end
@implementation PMOPictureController
// 1
@synthesize delegate = _delegate;
#pragma mark - Initializers
- (instancetype)initWithPictureURL:(NSURL *)url {
self = [super init];
if (self) {
_pictureWithUrl = [[PMOPictureWithURL alloc] initWithPictureURL:url];
PMODownloader *delegate = [[PMODownloader alloc] init];
delegate.receiver = self;
_delegate = delegate;
[self addObserverForDownloadTaskWithDownloader];
}
return self;
}
// 2
#pragma mark - Public API
- (void)downloadImage {
[self.delegate downloadDataFromURL:self.pictureWithUrl.imageURL];
}
//3
#pragma mark - Implementation of the PMODataHolder protocol
- (void)didDownloadedData:(NSData *)data {
if (data) {
[self willChangeValueForKey:@"image"];
self.pictureWithUrl.image = [UIImage imageWithData:data];
[self removeObserverForDownloadTask];
[self didChangeValueForKey:@"image"];
}
}
#pragma mark - Accessors
- (UIImage *)image {
return self.pictureWithUrl.image;
}
#pragma mark - Notification Events
- (void)didImageDownloadFailed {
NSLog(@"Image download failed");
}
#pragma mark - Notification helpers
- (void)addObserverForDownloadTaskWithDownloader {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didImageDownloadFailed)
name:PMODownloadFailed
object:nil];
}
- (void)removeObserverForDownloadTask {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Dealloc
- (void)dealloc {
[self removeObserverForDownloadTask];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment