2013-06-28 3 views
1
.

. Мой код ниже производит правильный объем данных в массиве, но данные дисплея будут принимать только последнее значение и отображение повторяется. Пример:Только последний магазин в массиве. Отобразится в виде таблицы.

Когда я выбрал первое изображение, первое изображение успешно отображается в виде таблицы. Когда я выбрал второе изображение, массив будет иметь 2 данных, но проблема в виде таблицы. Я получу 2 одинаковых изображения (второе выбранное изображение). Мой ожидаемый результат будет, когда будет выбрано второе изображение, первое изображение все равно останется, а второе отобразится в строке подпоследовательности.

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

NSLog(@"Collector in photoList %@",self.collector); 

for (int i = 0; i < collector.count; i++) { 
// define the block to call when we get the asset based on the url (below) 
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset) 
{ 
    ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation]; 
    CGImageRef iref = [imageRep fullResolutionImage]; 
    if (iref) { 
     galleryImage = [UIImage imageWithCGImage:iref]; 
     [self.tableView reloadData]; 
    } 
    NSLog(@"[imageRep filename] : %@", [imageRep filename]); 

}; 

NSLog(@"Collector %@",self.collector); 

// get the asset library and fetch the asset based on the ref url (pass in block above) 

ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc]init]; 
[assetslibrary assetForURL:[collector objectAtIndex:i] resultBlock:resultblock failureBlock:nil]; 

} 

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath 
    { 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

} 

cell.imageView.image = galleryImage; 
NSLog(@"Gallery image is %@",self.galleryImage); 
    return cell; 

}

EDITED!

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

NSLog(@"Collector in photoList %@",self.collector); 

for (int i = 0; i < collector.count; i++) { 
// define the block to call when we get the asset based on the url (below) 
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset) 
{ 
    ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation]; 
    CGImageRef iref = [imageRep fullResolutionImage]; 
    if (iref) { 
     galleryImage = [UIImage imageWithCGImage:iref]; 

     //Added mutable array for galleryImage 
     [photoCollector addObject:galleryImage]; 

     [self.tableView reloadData]; 
    } 
    NSLog(@"[imageRep filename] : %@", [imageRep filename]); 

}; 

NSLog(@"Collector %@",self.collector); 

// get the asset library and fetch the asset based on the ref url (pass in block above) 

ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc]init]; 
[assetslibrary assetForURL:[collector objectAtIndex:i] resultBlock:resultblock failureBlock:nil]; 

} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

} 

//Display image 
if(photoCollector.count != 0) 
{ 
    cell.imageView.image = [self.photoCollector objectAtIndex:indexPath.row]; 
} 

NSLog(@"This is in cellForRowAtIndexPath"); 
NSLog(@"Gallery image is %@",self.galleryImage); 

// Configure the cell... 
return cell; 

}

EDITED код на захватывающего didFinishPickingMediaWithInfo !!

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 

// Initialize View Controller 
PhotosListViewController *photoListViewController = [[PhotosListViewController alloc]initWithNibName:@"PhotosListViewController" bundle:nil]; 
ImageModel *imgModel = [[ImageModel alloc]init]; 

// get the ref url 
imageURL = [info valueForKey:UIImagePickerControllerReferenceURL]; 

//set the imageUrl to the imageModel url in property ? 
imgModel.url = imageURL; 

[self.collector addObject:imageURL]; 
photoListViewController.urlCollector = self.collector; 
NSLog(@"Collector in root %@",self.collector); 

[picker dismissViewControllerAnimated:YES completion:nil]; 
[self.navigationController pushViewController:photoListViewController animated:YES]; 

}

отредактированы полный код !!

RootViewController.m

- (void)imagePickerController:(UIImagePickerController *)picker  didFinishPickingMediaWithInfo:(NSDictionary *)info { 

// Initialize View Controller 
PhotosListViewController *photoListViewController = [[PhotosListViewController alloc]initWithNibName:@"PhotosListViewController" bundle:nil]; 

// get the ref url 
imageURL = [info valueForKey:UIImagePickerControllerReferenceURL]; 

[self.collector addObject:imageURL]; 
photoListViewController.urlCollector = self.collector; 

NSLog(@"Collector in root %@",self.collector); 

[picker dismissViewControllerAnimated:YES completion:nil]; 
[self.navigationController pushViewController:photoListViewController animated:YES]; 


} 

imagemodel.h

#import <Foundation/Foundation.h> 

typedef void(^handler)(UIImage *image); 

@interface ImageModel : NSObject 

@property (nonatomic, strong) NSURL *imageUrl; 

- (void)getImageWithCompletionHandler:(handler)completionBlock; 

@end 

ImageModel.m

#import "ImageModel.h" 
#import <MobileCoreServices/MobileCoreServices.h> 
#import <AssetsLibrary/AssetsLibrary.h> 

@implementation ImageModel 
@synthesize imageUrl; 

- (void)getImageWithCompletionHandler:(handler)completionBlock 
{ 
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset) 
    { 
    ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation]; 
    CGImageRef iref = [imageRep fullResolutionImage]; 
    if (iref) { 
     UIImage *image = [UIImage imageWithCGImage:iref]; 
     completionBlock(image); 
    } 

}; 

ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc]init]; 
[assetslibrary assetForURL:self.imageUrl resultBlock:resultblock failureBlock:nil]; 
} 
@end 

PhotoListViewController.m

- (void)viewDidLoad 
{ 

    [super viewDidLoad]; 
    test1 = [[UIImage alloc]init]; 
    self.imageModelObjects = [NSMutableArray array]; 
    for(NSURL *url in self.urlCollector) 
    { 
    ImageModel *imageModel = [[ImageModel alloc] init]; 
    imageModel.imageUrl = url; 
    [self.imageModelObjects addObject:imageModel]; 
    } 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

     }  

ImageModel *model = [self.imageModelObjects objectAtIndex:indexPath.row]; 

[model getImageWithCompletionHandler:^(UIImage *image) { 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     cell.imageView.image = image; 
    }); 

}]; 


return cell; 

}

+0

GalleryImage просто UIImage. Каждый раз, когда вы вызываете метод assetForURL: метод, galleryImage будет заменен. Столь очевидно, что после завершения цикла for ваша галереяImage будет содержать последнее изображение. Вместо galleryImage u вы можете использовать NSMutableArray и добавлять изображения в массив для каждой итерации в цикле. – iCoder

+0

Это работа (см. Мой отредактированный код выше), но это немного хлопотно, если пользователь удаляет изображение, добавленное в виде таблицы, потому что нужно удалить один за другим из другого массива. Есть ли другой простой способ поддерживать массив? – yukiko

+0

Его лучше рассмотреть наличие модели. Я редактировал код ниже, добавляя модель. Надеюсь, поможет :) . – iCoder

ответ

1
@interface ViewController() <UITableViewDataSource> 

@property (nonatomic, strong) NSMutableArray *images; 

@end 

@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.images = [[NSMutableArray alloc] init]; 

    NSLog(@"Collector in photoList %@",self.collector); 

    for (int i = 0; i < collector.count; i++) { 
     // define the block to call when we get the asset based on the url (below) 
     ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset) 
     { 
      ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation]; 
      CGImageRef iref = [imageRep fullResolutionImage]; 
      if (iref) { 
       [self.images addObject:[UIImage imageWithCGImage:iref]]; 
       [self.tableView reloadData]; 
      } 
      NSLog(@"[imageRep filename] : %@", [imageRep filename]); 

     }; 

     NSLog(@"Collector %@",self.collector); 

     // get the asset library and fetch the asset based on the ref url (pass in block above) 

     ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc]init]; 
     [assetslibrary assetForURL:[collector objectAtIndex:i] resultBlock:resultblock failureBlock:nil]; 

    } 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return self.images.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

    } 

    cell.imageView.image = self.images[indexPath.row]; 
    return cell; 
} 

@end 

Отредактировано:

imagemodel.h

#import <Foundation/Foundation.h> 

typedef void(^handler)(UIImage *image); 

@interface ImageModel : NSObject 

@property (nonatomic, strong) NSURL *imageURL; 

- (void)getImageWithCompletionHandler:(handler)completionBlock; 

@end 

ImageModel.m
#import "ImageModel.h" 

@implementation ImageModel 

- (void)getImageWithCompletionHandler:(handler)completionBlock 
{ 
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset) 
    { 
     ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation]; 
     CGImageRef iref = [imageRep fullResolutionImage]; 
     if (iref) { 
      UIImage *image = [UIImage imageWithCGImage:iref]; 
      completionBlock(image); 
     } 

    }; 

    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc]init]; 
    [assetslibrary assetForURL:self.imageURL resultBlock:resultblock failureBlock:nil]; 
} 

Controller.m

#import "ViewController.h" 
#import "ImageModel.h" 

@interface ViewController() 

@property (nonatomic, strong) NSMutableArray *imageModelObjects; 

@end 

@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.imageModelObjects = [NSMutableArray array]; 
    for(NSURL *url in self.collector) 
    { 
     ImageModel *imageModel = [[ImageModel alloc] init]; 
     imageModel.url = url; 
     [self.imageModelObjects addObject:imageModel] 
    } 

     //You can discard the collecter. IF u want the url, u can get from the self.imageModelObjects. 
     self.collector = nil; 

} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

    } 

    ImageModel *model = [self.imageModelObjects objectAtIndex:indexPath.row]; 

    [model getImageWithCompletionHandler:^(UIImage *image) { 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      cell.imageView.image = image; 
     }); 
    }]; 


    // Configure the cell... 
    return cell; 
} 
+0

Что я должен положить в комментарий там: - (void) viewDidLoad { [super viewDidLoad]; self.imageModelObjects = // Должен содержать объекты модели изображений. } – yukiko

+0

Для моего уточнения, в viewDidLoad контроллера.m, мы передаем URL-адрес imageModel.m для загрузки изображения? для (NSURL * url in self.collector) { ImageModel * imageModel = [[ImageModel alloc] init]; imageModel.url = url; [self.imageModelObjects addObject: imageModel] } – yukiko

+0

Вопрос не ясен. Наша цель - вместо хранения объекта NSURL в массиве, мы сохраняем собственный пользовательский объект, то есть ImageModel. Каждый объект ImageModel должен знать, какой url он имеет, а также должен возвращать изображение для URL-адреса. – iCoder

0
if (iref) 
{ 
    galleryImage = [UIImage imageWithCGImage:iref]; 

    //Added mutable array for galleryImage 
    [photoCollector addObject:galleryImage]; 
    [photoCollector retain]; 


    //[self.tableView reloadData]; 
} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *CellIdentifier = [NSString stringWithFormat:@"cell %d",indexPath.row]; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; 

     cell.textLabel.text = @"Hello"; 
     cell.imageView.image = [self.photoCollector objectAtIndex:indexPath.row]; 

    } 
    // Configure the cell. 
    return cell; 
}