在iOS中如果Model通知View,这会打破MVC吗?

时间:2015-12-05 11:39:22

标签: ios objective-c uitableview model-view-controller sdwebimage

当我创建用户(模型)对象时,我使用SDWebImage(在我的模型中)异步加载UITableViewCells中的用户图像。当我下载图像时,我在tableviewcell(View)中显示一个NSActivityIndi​​cator来代替图像。当图像下载后,我重新加载我的tableview。因为我把那些NSActivityIndi​​cators放在我的单元格中,我没有别的方法可以通过Notifications(在SDWEbimage方法完成处理程序内)来阻止它们。 所以问题是根据MVC架构这是否是一种正确的方法?

这是我的Model类(Employee)的片段:

    self.employeeID = [self stringValueForKey:@"id"];
    self.name = [self stringValueForKey:@"name"];
    self.company = [self stringValueForKey:@"company"];
    self.companyID = [self numberValueForKey:@"companyId"];
    self.photo = [UIImage imageNamed:@"photoPlaceholder"];

    // fetch Emploee photo
    NSString *photoURL = [NSString stringWithFormat:@"http://blabla.com//img/photo/%@.png",self.employeeID];
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:photoURL]
                                                          options:0
                                                         progress:^(NSInteger receivedSize, NSInteger expectedSize)
     {
     } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished)
     {
         if (image && finished)
         {
             self.photo = image;

             [[NSNotificationCenter defaultCenter] postNotificationName:@"IMAGE_FINISHED_DOWNLOADING" object:self];

             // make updates to database from Main Thread to avoid race conditions
             dispatch_async(dispatch_get_main_queue(), ^{

                NSFetchRequest *request = [NSFetchRequest new];
                [request setEntity:[NSEntityDescription entityForName:@"EmployeeCD" inManagedObjectContext:[AppDelegate getDelegate].managedObjectContext]];
                NSPredicate *predicate = [NSPredicate predicateWithFormat:@"employeeID == %@",self.employeeID];
                [request setPredicate:predicate];

                NSError *err;
                NSArray *arr = [[AppDelegate getDelegate].managedObjectContext executeFetchRequest:request error:&err];
                if ([arr count]) {
                    ((EmployeeCD*)arr.lastObject).photo = UIImagePNGRepresentation(image);
                    [[AppDelegate getDelegate] saveContext];
                }
            });
         }
         else
         {
             UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
             UIImage *img = [UIImage imageFromColor:[UIColor groupTableViewBackgroundColor]];
             UIImage *scaledImage = [img imageByScalingAndCroppingForSize:CGSizeMake(200, 200)];
             UIImage *roundImage = [UIImage roundImage:scaledImage imageView:imgView];
             self.photo = roundImage;

             [[NSNotificationCenter defaultCenter] postNotificationName:@"IMAGE_COULDNT_DOWNLOAD" object:self];
         }
     }];
}

enter image description here

1 个答案:

答案 0 :(得分:0)

不,你不能违反iOS MVC规则 MVC in iOS