return_type (^block_name)(param_type, param_type, ...)
int (^add)(int,int)
^return_type(param_type param_name, param_type param_name, ...) { ... return return_type; }
^(int number1, int number2){ return number1+number2 }
int (^add)(int,int) = ^(int number1, int number2){ return number1+number2; }
int resultFromBlock = add(2,2);
BOOL stop; for (int i = 0 ; i < [theArray count] ; i++) { NSLog(@"The object at index %d is %@",i,[theArray objectAtIndex:i]); if (stop) break; }
BOOL stop; int idx = 0; for (id obj in theArray) { NSLog(@"The object at index %d is %@",idx,obj); if (stop) break; idx++; }
[theArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){ NSLog(@"The object at index %d is %@",idx,obj); }];
- (void)removeAnimationView:(id)sender { [animatingView removeFromSuperview]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [UIView beginAnimations:@"Example" context:nil]; [UIView setAnimationDuration:5.0]; [UIView setAnimationDidStopSelector:@selector(removeAnimationView)]; [animatingView setAlpha:0]; [animatingView setCenter:CGPointMake(animatingView.center.x+50.0, animatingView.center.y+50.0)]; [UIView commitAnimations]; }
- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [UIView animateWithDuration:5.0 animations:^{ [animatingView setAlpha:0]; [animatingView setCenter:CGPointMake(animatingView.center.x+50.0, animatingView.center.y+50.0)]; } completion:^(BOOL finished) { [animatingView removeFromSuperview]; }]; }
@interface IODItem : NSObject <NSCopying>
#import <Foundation/Foundation.h> @interface IODItem : NSObject <NSCopying> @property (nonatomic,strong) NSString* name; @property (nonatomic,strong) float price; @property (nonatomic,strong) NSString* pictureFile; @end
— (id)copyWithZone:(NSZone *)zone
. Until this method is added, the class will be considered incomplete. Add the following to IODItem.m before @end : - (id)copyWithZone:(NSZone *)zone { IODItem *newItem = [[IODItem alloc] init]; newItem.name = _name; newItem.price = _price; newItem.pictureFile = _pictureFile; return newItem; }
- (id)initWithName:(NSString *)name andPrice:(NSNumber *)price andPictureFile:(NSString *)pictureFile { if(self = [self init]) { _name = name; _price = price; _pictureFile = pictureFile; } return self; }
- (id)initWithName:(NSString*)inName andPrice:(float)inPrice andPictureFile:(NSString*)inPictureFile;
#import "IODItem.h"
@property (nonatomic,strong) NSMutableDictionary* orderItems;
#import "ViewController.h" #import "IODOrder.h" @interface ViewController () @property (assign, nonatomic) NSInteger currentItemIndex; @property (strong, nonatomic) NSMutableArray *inventory; @property (strong, nonatomic) IODOrder *order;
- (void)viewDidLoad { [super viewDidLoad]; self.currentItemIndex = 0; self.order = [[IODOrder alloc] init]; }
#import "ViewController.h" #import "IODOrder.h" @interface ViewController () @property (assign, nonatomic) NSInteger currentItemIndex; @property (strong, nonatomic) NSMutableArray *inventory; @property (strong, nonatomic) IODOrder *order; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.currentItemIndex = 0; self.order = [[IODOrder alloc] init]; }
#define INVENTORY_ADDRESS @"http://adamburkepile.com/inventory/"
+ (NSArray *)retrieveInventoryItems { // 1 — NSMutableArray *inventory = [[NSMutableArray alloc] init]; NSError *error = nil; // 2 — NSArray *jsonInventory = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:INVENTORY_ADDRESS]] options:kNilOptions error:&error]; // 3 — [jsonInventory enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { NSDictionary *item = obj; [inventory addObject:[[IODItem alloc] initWithName:item[@"Name"] andPrice:item[@"Price"] andPictureFile:item[@"Image"]]]; }]; // 4 — return [inventory copy]; }
+ (NSArray*)retrieveInventoryItems;
@property (strong, nonatomic) dispatch_queue_t queue;
self.queue = dispatch_queue_create("com.adamburkepile.queue",nil);
self.ibChalkboardLabel.text = @"Loading inventory..."; self.inventory = [[IODItem retrieveInventoryItems] mutableCopy]; self.ibChalkboardLabel.text = @"Inventory Loaded\n\nHow can I help you?";
dispatch_async(self.queue, ^{ self.inventory = [[IODItem retrieveInventoryItems] mutableCopy]; dispatch_async(dispatch_get_main_queue(), ^{ self.ibChalkboardLabel.text = @"Inventory Loaded\n\nHow can I help you?"; }); });
- (IODItem *)findKeyForOrderItem:(IODItem *)searchItem { //1 - NSIndexSet *indexes = [[self.orderItems allKeys] indexesOfObjectsPassingTest:^BOOL(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { IODItem *key = obj; return ([searchItem.name isEqualToString:key.name] && searchItem.price == key.price); }]; //2 - if([indexes count] >=1) { IODItem *key = [self.orderItems allKeys][[indexes firstIndex]]; return key; } //3 - return nil; }
- (IODItem*)findKeyForOrderItem:(IODItem*)searchItem;
- (void)updateCurrentInventoryItem { if (self.currentItemIndex >=0 && self.currentItemIndex < [self.inventory count]) { IODItem* currentItem = self.inventory[self.currentItemIndex]; self.ibCurrentItemLabel.text = currentItem.name; self.ibCurrentItemLabel.adjustsFontSizeToFitWidth = YES; self.ibCurrentItemImageView.image = [UIImage imageNamed:[currentItem pictureFile]]; } }
- (void)updateInventoryButtons { if (!self.inventory || ![self.inventory count]) { self.ibAddItemButton.enabled = NO; self.ibRemoveItemButton.enabled = NO; self.ibNextItemButton.enabled = NO; self.ibPreviousItemButton.enabled = NO; self.ibTotalOrderButton.enabled = NO; } else { if (self.currentItemIndex <= 0) { self.ibPreviousItemButton.enabled = NO; } else { self.ibPreviousItemButton.enabled = YES; } if (self.currentItemIndex >= [self.inventory count]-1) { self.ibNextItemButton.enabled = NO; } else { self.ibNextItemButton.enabled = YES; } IODItem* currentItem = self.inventory[self.currentItemIndex]; if (currentItem) { self.ibAddItemButton.enabled = YES; } else { self.ibAddItemButton.enabled = NO; } if (![self.order findKeyForOrderItem:currentItem]) { self.ibRemoveItemButton.enabled = NO; } else { self.ibRemoveItemButton.enabled = YES; } if (![self.order.orderItems count]) { self.ibTotalOrderButton.enabled = NO; } else { self.ibTotalOrderButton.enabled = YES; } } }
[self updateInventoryButtons];
dispatch_async(queue, ^{ self.inventory = [[IODItem retrieveInventoryItems] mutableCopy]; dispatch_async(dispatch_get_main_queue(), ^{ [self updateInventoryButtons]; [self updateCurrentInventoryItem]; self.ibChalkboardLabel.text = @"Inventory Loaded\n\nHow can I help you?"; }); });
- (IBAction)ibaLoadPreviousItem:(UIButton *)sender { self.currentItemIndex--; [self updateCurrentInventoryItem]; [self updateInventoryButtons]; } - (IBAction)ibaLoadNextItem:(UIButton *)sender { self.currentItemIndex++; [self updateCurrentInventoryItem]; [self updateInventoryButtons]; }
- (NSMutableDictionary *)orderItems{ if (!_orderItems) { _orderItems = [[NSMutableDictionary alloc] init]; } return _orderItems; }
- (NSString*)orderDescription { // 1 - NSMutableString* orderDescription = [[NSMutableString alloc] init]; // 2 - NSArray* keys = [[self.orderItems allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { IODItem* item1 = (IODItem*)obj1; IODItem* item2 = (IODItem*)obj2; return [item1.name compare:item2.name]; }]; // 3 - [keys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { IODItem* item = (IODItem*)obj; NSNumber* quantity = (NSNumber*)[self.orderItems objectForKey:item]; [orderDescription appendFormat:@"%@ x%@\n", item.name, quantity]; }]; // 4 - return [orderDescription copy]; }
- (void)updateCurrentInventoryItem; - (void)updateInventoryButtons;
- (void)updateOrderBoard { if (![self.order.orderItems count]) { self.ibChalkboardLabel.text = @"No Items. Please order something!"; } else { self.ibChalkboardLabel.text = [self.order orderDescription]; } }
dispatch_async(self.queue, ^{ self.inventory = [[IODItem retrieveInventoryItems] mutableCopy]; dispatch_async(dispatch_get_main_queue(), ^{ [self updateOrderBoard]; //<---- [self updateInventoryButtons]; [self updateCurrentInventoryItem]; self.ibChalkboardLabel.text = @"Inventory Loaded\n\nHow can I help you?"; }); });
- (void)addItemToOrder:(IODItem*)inItem { // 1 - IODItem* key = [self findKeyForOrderItem:inItem]; // 2 - - if (!key) { [self.orderItems setObject:[NSNumber numberWithInt:1] forKey:inItem]; } else { // 3 - - NSNumber* quantity = self.orderItems[key]; int intQuantity = [quantity intValue]; intQuantity++; // 4 - [self.orderItems removeObjectForKey:key]; [self.orderItems setObject:[NSNumber numberWithInt:intQuantity] forKey:key]; } }
- (void)removeItemFromOrder:(IODItem*)inItem { // 1 - IODItem* key = [self findKeyForOrderItem:inItem]; // 2 - , if (key) { // 3 - , NSNumber* quantity = self.orderItems[key]; int intQuantity = [quantity intValue]; intQuantity--; // 4 - [[self orderItems] removeObjectForKey:key]; // 5 - 0 if (intQuantity) [[self orderItems] setObject:[NSNumber numberWithInt:intQuantity] forKey:key]; } }
- (void)addItemToOrder:(IODItem*)inItem; - (void)removeItemFromOrder:(IODItem*)inItem;
- (IBAction)ibaRemoveItem:(UIButton *)sender { IODItem* currentItem = self.inventory[self.currentItemIndex]; [self.order removeItemFromOrder:currentItem]; [self updateOrderBoard]; [self updateCurrentInventoryItem]; [self updateInventoryButtons]; } - (IBAction)ibaAddItem:(UIButton *)sender { IODItem* currentItem = self.inventory[self.currentItemIndex]; [self.order addItemToOrder:currentItem]; [self updateOrderBoard]; [self updateCurrentInventoryItem]; [self updateInventoryButtons]; }
- (IBAction)ibaRemoveItem:(UIButton *)sender { IODItem* currentItem = [self.inventory objectAtIndex:self.currentItemIndex]; [self.order removeItemFromOrder:currentItem]; [self updateOrderBoard]; [self updateCurrentInventoryItem]; [self updateInventoryButtons]; UILabel* removeItemDisplay = [[UILabel alloc] initWithFrame:self.ibCurrentItemImageView.frame]; removeItemDisplay.center = self.ibChalkboardLabel.center; removeItemDisplay.text = @"-1"; removeItemDisplay.textAlignment = NSTextAlignmentCenter; removeItemDisplay.textColor = [UIColor redColor]; removeItemDisplay.backgroundColor = [UIColor clearColor]; removeItemDisplay.font = [UIFont boldSystemFontOfSize:32.0]; [[self view] addSubview:removeItemDisplay]; [UIView animateWithDuration:1.0 animations:^{ removeItemDisplay.center = [self.ibCurrentItemImageView center]; removeItemDisplay.alpha = 0.0; } completion:^(BOOL finished) { [removeItemDisplay removeFromSuperview]; }]; } - (IBAction)ibaAddItem:(UIButton *)sender { IODItem* currentItem = [self.inventory objectAtIndex:self.currentItemIndex]; [self.order addItemToOrder:currentItem]; [self updateOrderBoard]; [self updateCurrentInventoryItem]; [self updateInventoryButtons]; UILabel* addItemDisplay = [[UILabel alloc] initWithFrame:self.ibCurrentItemImageView.frame]; addItemDisplay.text = @"+1"; addItemDisplay.textColor = [UIColor whiteColor]; addItemDisplay.backgroundColor = [UIColor clearColor]; addItemDisplay.textAlignment = NSTextAlignmentCenter; addItemDisplay.font = [UIFont boldSystemFontOfSize:32.0]; [[self view] addSubview:addItemDisplay]; [UIView animateWithDuration:1.0 animations:^{ [addItemDisplay setCenter:self.ibChalkboardLabel.center]; [addItemDisplay setAlpha:0.0]; } completion:^(BOOL finished) { [addItemDisplay removeFromSuperview]; }]; }
- (float)totalOrder { // 1 - __block float total = 0.0; // 2 - float (^itemTotal)(float,int) = ^float(float price, int quantity) { return price * quantity; }; // 3 - [self.orderItems enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { IODItem* item = (IODItem*)key; NSNumber* quantity = (NSNumber*)obj; int intQuantity = [quantity intValue]; total += itemTotal([item.price floatValue], intQuantity); }]; // 4 - return total; }
- (float)totalOrder;
- (IBAction)ibaCalculateTotal:(UIButton *)sender { float total = [self.order totalOrder]; UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Total" message:[NSString stringWithFormat:@"$%0.2f",total] preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:@"Close" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { [alert dismissViewControllerAnimated:YES completion:nil]; }]; [alert addAction:cancelButton]; [self presentViewController:alert animated:YES completion:nil]; }
// , - (void)doMathWithBlock:(int (^)(int, int))mathBlock { self.label.text = [NSString stringWithFormat:@"%d", mathBlock(3, 5)]; } // - (IBAction)buttonTapped:(id)sender { [self doMathWithBlock:^(int a, int b) { return a + b; }]; }
// @property (strong) int (^mathBlock)(int, int); // - (void)doMathWithBlock:(int (^)(int, int))mathBlock { self.mathBlock = mathBlock; } // - (IBAction)buttonTapped:(id)sender { [self doMathWithBlock:^(int a, int b) { return a + b; }]; } // ... - (IBAction)button2Tapped:(id)sender { self.label.text = [NSString stringWithFormat:@"%d", self.mathBlock(3, 5)]; } }
//typedef typedef int (^MathBlock)(int, int); // , typedef @property (strong) MathBlock mathBlock; // - (void)doMathWithBlock:(MathBlock) mathBlock { self.mathBlock = mathBlock; } // - (IBAction)buttonTapped:(id)sender { [self doMathWithBlock:^(int a, int b) { return a + b; }]; } // ... - (IBAction)button2Tapped:(id)sender { self.label.text = [NSString stringWithFormat:@"%d", self.mathBlock(3, 5)]; }
NSArray * array; [array enum
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { code }
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { // Do something }];
Source: https://habr.com/ru/post/309846/
All Articles