Skip to content

Instantly share code, notes, and snippets.

@jaanus
Created January 25, 2015 08:07
Show Gist options
  • Save jaanus/d12aec8b6fc90cd9d0de to your computer and use it in GitHub Desktop.
Save jaanus/d12aec8b6fc90cd9d0de to your computer and use it in GitHub Desktop.
+[NSData dataWithContentsOfURL:] will cause NSProgress to report progress.
#import <Foundation/Foundation.h>
static void *ProgressObserverContext = &ProgressObserverContext;
@interface MyObject: NSObject
@property (strong, nonatomic) NSProgress *progress;
@end
@implementation MyObject
- (instancetype)init {
if (self = [super init]) {
self.progress = [NSProgress progressWithTotalUnitCount:1];
[self.progress addObserver:self
forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
options:NSKeyValueObservingOptionInitial
context:ProgressObserverContext];
[self.progress becomeCurrentWithPendingUnitCount:1];
// Either of the following next two lines will cause progress to be reported.
NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:@"/etc/hosts"]];
// NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.example.com"]];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
{
if (context == ProgressObserverContext)
{
NSProgress *progress = object;
NSLog(@"fraction completed: %f", progress.fractionCompleted);
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object
change:change context:context];
}
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
MyObject *object = [[MyObject alloc] init];
}
}
@jaanus
Copy link
Author

jaanus commented Jan 25, 2015

To try, just copy and paste into CodeRunner.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment