Objective Blocks
Block genel anlamda açıklamak gerekirse bir fonksiyon içerisindeki anonim fonksiyondur. Javascript diline aşina olanlar için bu konuyu anlamak hiç zor olmayacak. Block yapısının en önemli avantajı programcıları uzun uzadıya kod yazmaktan kurtarması ve yazılan kodların daha anlaşılır olmasını sağlamasıdır
type (^block_name) (type_arguments) = ^ return_type (type arguments) {
// kodlar buraya
};
Bir örnek vermek gerekirse block şu şekilde tanımlanabilir :
typedef void (^ PictureGlobalBlock)(NSString *imStr, UIImage *image, NSUInteger len);
yukarıdaki örnek global değişken olarak block tanımlamasına örnektir.
Bunun dışında fonksiyon parametresi olarak da block tanımlanabilir.
-(void) loadImageWithURL:(NSString *)url success:(void (^)(UIImage *img , NSString *url))success failure:(void (^)(NSString *url , NSError *error))failure ;
yukarıdaki örnekte eğer resim yüklemesi başarılı ise success bloğu , değil ise failure bloğu çalıştırılacak.
Örnek uygulamada block kullanılarak urlden resim yükleniyor. Bunun için
PictureLoader.h :
#import <Foundation/Foundation.h>
// url , image , dataLength
typedef void (^ PictureGlobalBlock)(NSString *imStr, UIImage *image, NSUInteger len);
@interface PictureLoader : NSObject
{
}
-(id)init;
/*
@ gloabal block kullanarak resmi yukler. Resim yuklendiginde block cagirilir.
*/
-(void)loadImageWithURL:(NSString *) imageURL GlobalBlock:(PictureGlobalBlock) block;
/*
@ block kullanilarak resim yuklenir. Resim yuklemesi tamamlandiginda success block, eger hata varsa failure block cagirilir. Failure durumunu gostermek icin bu fonksiyon su an sadece jpg turunde resimleri yukleyecek. Aslinda her tur resim formati yuklenebilir.
*/
-(void) loadImageWithURL:(NSString *)url success:(void (^)(UIImage *img , NSString *url))success failure:(void (^)(NSString *url , NSError *error))failure ;
@end
PictureLoader.m :
#import “PictureLoader.h”
@implementation PictureLoader
-(id)init
{
if(self = [super init])
{
}
return self;
}
-(void)loadImageWithURL:(NSString *)imageURL GlobalBlock:(PictureGlobalBlock)block
{
// resim urlsi olusturma
NSURL *URL = [NSURL URLWithString:imageURL];
NSData *data = [NSData dataWithContentsOfURL:URL];
NSUInteger dataLength = [data length]; // 1 – DATA LENGTH
UIImage *img = [UIImage imageWithData:data]; // 2- image
block(imageURL,img,dataLength); // call the block
}
-(void)loadImageWithURL:(NSString *)url success:(void (^)(UIImage *, NSString *))success failure:(void (^)(NSString *, NSError *))failure
{
// failure demo
NSString *extension = [url substringWithRange:NSMakeRange(url.length-3, 3)];
if(! ([extension isEqualToString:@”JPG”] || [extension isEqualToString:@”jpg”]))
{
NSDictionary *userInfo = @{@”Reason”: @”resim jpg formatinda olmalidir.”};
NSError *err= [NSError errorWithDomain:@”Err” code:-11 userInfo:userInfo];
failure(url, err);
return;
}
NSURL *URL = [NSURL URLWithString:url];
NSData *data = [NSData dataWithContentsOfURL:URL];
UIImage *img = [UIImage imageWithData:data];
success (img,url);
}
@end
ViewController.h:
#import <UIKit/UIKit.h>
#import “PictureLoader.h”
#define IMAGE_URL @“http://cdn.wonderfulengineering.com/wp-content/uploads/2014/03/high-quality-wallpaper-4.jpg”
@interface ViewController : UIViewController
{
UIImageView *imView;
}
@end
ViewController.m:
#import “ViewController.h”
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.
imView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
[self.view addSubview:imView]; [self loadingWithGlobalBlock];}
-(void)loadingWithGlobalBlock
{
NSLog(@”Processing…”);
PictureLoader *loader = [[PictureLoader alloc]init];
[loader loadImageWithURL:IMAGE_URL GlobalBlock:^(NSString *imStr, UIImage *image, NSUInteger len) {NSLog(@”data length : %d” , len);
NSLog(@”loaded successfully”);
imView.image = image;
}];
}
-(void)loadingWithBlock
{
NSLog(@”Processing…”);
PictureLoader *loader = [[PictureLoader alloc]init];
[loader loadImageWithURL:IMAGE_URL success:^(UIImage *img, NSString *url) {NSLog(@”loaded successfully”);
imView.image = img;
} failure:^(NSString *url, NSError *error) {
}];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}
@end