- (IBAction)login:(UIButton *)sender {
sender.enabled = NO;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"_login": @"bar", @"_pass" : @"123"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
sender.enabled = YES;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
sender.enabled = YES;
}];
}
...
Customers *customers;
NSMutableDictionary *dictionaryCustomers;
NSArray *sortedKeys = nil;
...
for (NSDictionary *dictionary in [responseData objectForKey:@"data_list"]) {
customers = [[Customers alloc] init];
for (NSString *key in [dictionary allKeys]) {
if ([customers respondsToSelector:NSSelectorFromString(key)]) {
[customers setValue:[dictionary objectForKey:key] forKey:key];
}
}
//например по имени индексируем
NSString *fisrtSymbol = [[customers.name substringFromIndex:1] uppercaseString];
if ([dictionaryCustomers.allKeys containsObject:fisrtSymbol] == NO)
{
dictionaryCustomers[fisrtSymbol] = [NSMutableArray new];
}
[dictionaryCustomers[fisrtSymbol] addObject:customers];
}
sortedKeys = [dictionaryCustomers.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
return [obj1 compare:obj2];
}]
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return dictionaryCustomers.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dictionaryCustomers[sortedKeys[section]] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Customers *c = [dictionaryCustomers[sortedKeys[indexPath.section]] obkectAtIndex:indexPath.row];
...
return cell;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return sortedKeys;
}
@interface MyViewController ()
@property NSMutableDictionary *dictionaryCustomers; // исходные которые были заполненны из responseData
@property NSArray *sortedKeys; // исходные которые были заполненны из responseData
@property NSDictionary *currentDictionaryCustomers;
@property NSArray *currentSortedKeys;
@end
@implemented MyViewController
- (void)parseResponse:(id)responseData
{
// парсим ответ
self.dictionaryCustomers = ...
self.sortedKeys = ...
self.currentDictionaryCustomers = self.dictionaryCustomers;
self.currentSortedKeys = self.sortedKeys;
}
- (void)filterCustomers:(NSString *)sFilter
{
NSMutableDictionary *result = [NSMutableDictionary new];
for (NSString *key in [self.dictionaryCustomers allKeys])
{
for (Customers *customer in self.dictionaryCustomers[key])
{
if (<customer.company содержит sFilter>)
{
if ([result.allKeys containsObject:key] == NO) result[key] = [NSmutableArray new];
[result[key] addObject:customer];
}
}
}
self.currentDictionaryCustomers = result;
self.currentSortedKeys = [result.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
return [obj1 compare:obj2];
}]
[self.tableView reloadData];
}
// тут заполняем tableView из self.currentDictionaryCustomers и self.currentSortedKeys
@end
-(void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needChangeLabel:) name:@"WBCAddWaterViewControllerChangeLabelNotification" object:nil];
}
- (void)needChangeLabel:(NSNotification *)n
{
NSLog(@"%@", n.userInfo);
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"WBCAddWaterViewControllerChangeLabelNotification" object:nil];
}
NSDictionary *userInfo = @{@"key1" : @"value1", @"key2" : @"value2"};
[[NSNotificationCenter defaultCenter] postNotificationName:@"WBCAddWaterViewControllerChangeLabelNotification" object:nil userInfo:userInfo];
@interface MyViewController ()
@property (strong, nonatomic) SDReachability *reachability;
@end
@implementation MyViewController
//...
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self monitorReachability];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear];
[self stopMonitorReachability];
}
- (void)monitorReachability
{
self.reachability = [SDReachability reachabilityWithTarget:self action:@selector(reachabilityChanged:)];
}
- (void)stopMonitorReachability
{
self.reachability = nil;
}
- (void)reachabilityChanged:(SDReachability *)reachability
{
switch (reachability.reachabilityStatus)
{
case SDNotReachable:
{
NSLog(@"Connection lost");
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"Connection lost" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
// тут делаеш с view всё что захочешь
break;
}
case SDReachableViaWiFi:
NSLog(@"Connected via WiFi");
break;
case SDReachableViaWWAN:
NSLog(@"Connected via WWAN");
break;
}
}
@end
@interface MyRootViewController ()
@property (strong, nonatomic) SDReachability *reachability;
@end
@implementation MyRootViewController
//...
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self monitorReachability];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear];
[self stopMonitorReachability];
}
- (void)monitorReachability
{
self.reachability = [SDReachability reachabilityWithTarget:self action:@selector(reachabilityChanged:)];
}
- (void)stopMonitorReachability
{
self.reachability = nil;
}
- (void)reachabilityChanged:(SDReachability *)reachability
{
switch (reachability.reachabilityStatus)
{
case SDNotReachable:
{
NSLog(@"Connection lost");
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"Connection lost" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[self.navigationController popToRootViewController]; // убираем все контроллеры из стека
// тут модифицируешь self.view - например добавляеш на неё label "Connection Lost"
break;
}
case SDReachableViaWiFi:
NSLog(@"Connected via WiFi");
break;
case SDReachableViaWWAN:
NSLog(@"Connected via WWAN");
break;
}
}
@end
|----------------------------|
| |
| |
| |
| tableView |
| |
| |
|----------------------------|
|----------------------------|
| ToolBarView. |
|----------------------------|
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.users.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.users[section].comments.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0)
{
UITableViewCell *cell = [[self tableViewAllCheckins] dequeueReusableCellWithIdentifier:@"UserCell"];
NSDictionary *userInfo = self.users[indexPath.section];
// заполнение ячейки User-а
return cell;
}
else
{
CommentViewCell *commentCell = [[self tableViewAllCheckins] dequeueReusableCellWithIdentifier:@"CommentCell"];
UserInfo *userInfo = self.users[indexPath.section];
CommentInfo *comment = userInfo.comments[indexPath.row - 1]; // так как нулевая ячейка в секции принадлежит пользователю, а первая ячейка принадлежит нулевому комментарию, то надо сделать минус 1
// заполнение ячейки Comment-а
return commentCell;
}
}
//как-то так должен выглядеть MyImagesView.m файл
@interface MyImagesView ()
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, assign) int currentImage;
@property (nonatomic, assign) int totalImages;
@end
@implementation
/*
* этот метод надо вызывать в таймере. обязательно в Main Thread
*/
- (void)showNextImage
{
assert([NSThread isMainThread] == YES);
self.currentImage ++;
if (self.currentImage == self.totalImages)
{
// что бы отображать картинки циклически
self.currentImage = 0;
}
UIImageView *newImageView = [[UIImageView alloc] initWithFrame:self.bounds];
newImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"image_name%i.png", self.currentImage]];
[self.imageView removeFromSuperview]; // убираем прирыдущий кадр из view-хи (затираем сильную ссылку номер 1)
self.imageView = nil; // убираем сильную ссылку номер два (тут UIImageView должна выгрузиться из памяти, а с ней и UIImage)
[self addSubview:newImageView]; // закидываем новый кадр во view-ху (создаём сильную ссылку номер 1)
self.imageView = newImageView; // сохраняем ссылку на новый кадр что бы иметь в следующем вызове метода showNextImage ссылку на предыдущий кадр (создаём сильную ссылку номер 2)
}
@end
newImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"image_name%i.png", self.currentImage]];
на:NSString *imageName = [NSString stringWithFormat:@"image_name%i", self.currentImage];
newImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:@"png"]];
//файл A.h
@protocol ADelegate <NSObject>
- (void)aDelegateMethod;
@end
@interface A : NSObject
@property (nonatomic, weak) id<ADelegate> delegate;
/*
Описывая делегат таким образом мы скрываем объект за протоколом ADelegate.
В вашем случае модель не будет знать что у неё делегат это контроллер, модель будет
думать что там есть некий объект который отвечает на ADelegate протокол и кто там конкретно не важно
*/
@end
//файл B.h
#import "A.h"
@interface B : NSObject <ADelegate>
@end
//файл B.m
@implementation B
- (void)foo
{
A *a = [A new];
a.delegate = self;
}
#pragma mark - ADelegate Protocol
- (void)aDelegateMethod
{
}
@end