(Xcode 5,ios7,arc)i have a view controller,it have a tableview,The problem is that cell loading picture, make a memory leak. I have repeatedly push the view controller ,and then back, memory continues to increase. My English is not good, do not know whether the clear expression. How to solve the problem of excessive picture memory, hope to master for help.Here is the code:
#implementation SearchCell
-(void)dealloc
{
_imageV = nil;
_titleL = nil;
_infoL = nil;
_countL = nil;
}
+(instancetype) cellWithTableView:(UITableView *)tableView model:(SearchModel *)model
{
static NSString* strID = #"SPECIALCELL";
SearchCell* cell = [tableView dequeueReusableCellWithIdentifier:strID];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:#"SearchCell" owner:nil options:nil] lastObject];
}
[cell setSearchCellModel:model];
return cell;
}
-(void) setSearchCellModel:(SearchModel*)model
{
UIImage* img = [[SDWebImageManager sharedManager] imageWithURL:[NSURL URLWithString:model.tvImgURL]];
self.imageV.image = img;
self.titleL.text = model.tvName;
self.infoL.text = model.tvInfo;
self.countL.text = model.tvCount;
}
hear
you get the your answer for this question ... you need to use lasy loading image view..
i would like to give hint for that.
1). first you need to save image on document directory unique name(url name) then check if image are there in document directory then you fetch image from document directory folder and when you save image that time you save image small size use this link code easily solve your problem.
Related
I'm running into a bit of a strange problem here. One of my NSURLSessions is in charge of getting information for restaurant information that I have stored (restaurant name, restaurant's logo URL, etc), and then the second NSURLSession is in charge of using the restaurant's logo URL to retrieve the specific image and set it for each UITableView's cell.
The problem, however, is that my UITableView does not load anything at all sometimes so the cells are empty, but at other times when I add an extra [_tableView reload] in the NSURLSessions' completion block in the fetchPosts method, it'll work, but then the cells will stop displaying anything again if I re-run it. Something is definitely wrong. Have a look at my code below:
#import "MainViewController.h"
#import "SWRevealViewController.h"
#import "RestaurantNameViewCell.h"
#import "RestaurantList.h"
#interface MainViewController ()
#end
#implementation MainViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//List of restaurants needed to load home page
_restaurantInformationArray = [[NSMutableArray alloc] init];
self.tableView.dataSource = self;
self.tableView.delegate = self;
//setup for sidebar
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.sidebarButton setTarget: self.revealViewController];
[self.sidebarButton setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
//Get list of restaurants and their image URLs
[self fetchPosts];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_restaurantInformationArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RestaurantNameViewCell *cell = (RestaurantNameViewCell *)[_tableView dequeueReusableCellWithIdentifier:#"restaurantName" forIndexPath:indexPath];
RestaurantList *currentRestaurant = [_restaurantInformationArray objectAtIndex:indexPath.row];
cell.restaurantName.text = currentRestaurant.name;
cell.imageAddress = currentRestaurant.imageURL;
cell.restaurantClicked = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapDetected:)];
cell.restaurantClicked.numberOfTapsRequired = 1;
cell.restaurantLogo.userInteractionEnabled = YES;
[cell.restaurantLogo addGestureRecognizer:cell.restaurantClicked];
cell.restaurantLogo.tag = indexPath.row;
//Add restaurant logo image:
NSString *URL = [NSString stringWithFormat:#"http://private.com/images/%#.png",cell.imageAddress];
NSURL *url = [NSURL URLWithString:URL];
NSURLSessionDownloadTask *downloadLogo = [[NSURLSession sharedSession]downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
cell.restaurantLogo.image = downloadedImage;
}];
[downloadLogo resume];
return cell;
}
-(void)fetchPosts {
NSString *address = #"http://localhost/xampp/restaurants.php";
NSURL *url = [NSURL URLWithString:address];
NSURLSessionDataTask *downloadRestaurants = [[NSURLSession sharedSession]dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError *someError;
NSArray *restaurantInfo = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&someError];
for(NSDictionary *dict in restaurantInfo) {
RestaurantList *newRestaurant = [[RestaurantList alloc]init];
newRestaurant.name = [dict valueForKey:#"name"];
newRestaurant.imageURL = [dict valueForKey:#"image"];
[_restaurantInformationArray addObject:newRestaurant];
//Refresh table view to make sure the cells have info AFTER the above stuff is done
[_tableView reloadData];
}
}];
[downloadRestaurants resume];
}
#end
It's probably a very stupid mistake that I'm making, but I'm not certain how I should correct this. I'm new to iOS development, so would greatly appreciate some guidance :)
Besides assuming that your network requests aren't erroring (you should at least log if there are network errors), there are threading issues.
Your NSURLSession callback probably runs on a background thread. This makes it unsafe to call UIKit (aka - [_tableView reloadData]). UIKit isn't thread safe. This means invoking any of UIKit's APIs from another thread creates non-deterministic behavior. You'll want to run that piece of code on the main thread:
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView reloadData];
});
Likewise for fetching the images. It's slightly more complicated because of table view cell reuse which could cause the wrong image to display when scrolling. This is because the same cell instance is used for multiple values in your array as the user scrolls. When any of those callbacks trigger, it'll replace whatever image happens to be in that cell. The generally steps to reproduce this is as follows:
TableView requests 5 cells
MainViewController requests 5 images (one for each cell)
User scrolls down one cell
The first cell gets reused as the 6th cell.
MainViewController requests another image for the 6th cell.
The 6th image is retrieved, the callback is triggered, image of the first cell is set to image #6.
The 1st image is retrieved, the callback is triggered, image of the first cell is set to image #1 (incorrect).
You'll need to make sure the cell is displaying the correct cell before attempting to assign the image to it. If you rather not implement that logic for image fetching in cells, you could use SDWebImage instead. Using SDWebImage's [UIImageView sd_setImageWithURL:] is thread safe (it will set the image on the main thread).
Side notes:
You only need to reload data once all your changes are in _restaurantInformationArray, and not every time in the for loop.
I want to pass a UIImage from a View Controller to another one, but it doesn't work. I actually get (null) if I log the UIImage Value in the second View Controller.
The Image File comes from parse.com. And it works absolutely fine in the first view controller. But as soon as I pass it to the second view controller, the image won't work there.
Here's the code:
My prepareForSegue in the .m file of the firstViewController (BookListTableViewController)
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"ShowBookDetailSegue"]) {
NSIndexPath *indexPath = [self.bookListTableView indexPathForSelectedRow];
ParseBookDetailTableViewController *pbdtvc = segue.destinationViewController;
PFObject *tempObject = [totalStrings objectAtIndex:indexPath.row];
PFFile *eventImage = [tempObject objectForKey:#"bookImage"];
if(eventImage != NULL)
{
[eventImage getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error)
{
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
pbdtvc.bookImageDetail = thumbnailImage;
}];
}
my .h file of the secondViewController (ParseBookDetailViewController)
#property (strong, nonatomic) UIImage* bookImageDetail;
#property (strong, nonatomic) IBOutlet UIImageView *bookImageDetailView;
viewDidLoad of my .m file of the secondViewController (ParseBookDetailViewController)
NSLog(#"%#",bookImageDetail);
[bookImageDetailView setImage:bookImageDetail];
As I said: in the original View Controller the Image is correct. I can log it and even set it there to an ImageView. But in the second view controller there is (null).
Glad for help, thanks..
EDIT:
This is the code from my cellForRowAtIndexPath.
PFObject *tempObject = [totalStrings objectAtIndex:indexPath.row];
//cell.textLabel.text = [tempObject objectForKey:#"bookTitle"];
cell.titleTextField.text = [tempObject objectForKey:#"bookTitle"];
cell.bookAutor1Label.text = [tempObject objectForKey:#"bookAutor1"];
cell.isbnLabel.text = [tempObject objectForKey:#"bookISBN"];
cell.statusLabel.text = [tempObject objectForKey:#"bookStatus"];
cell.yearLabel.text = [tempObject objectForKey:#"BookDate"];
if ([cell.statusLabel.text isEqualToString:#"nicht verfügbar"]) {
cell.statusLabel.tintColor = [UIColor redColor];
cell.dotImageIcon.image = [UIImage imageNamed:#"dot_red.png"];
}else if ([cell.statusLabel.text isEqualToString:#"verfügbar"]){
cell.statusLabel.tintColor = [UIColor greenColor];
cell.dotImageIcon.image = [UIImage imageNamed:#"dot_green.png"];
}
PFFile *eventImage = [tempObject objectForKey:#"bookImage"];
if(eventImage != NULL)
{
[eventImage getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error)
{
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
prepareForSegueImage = thumbnailImage;
[cell.bookImageView setImage:thumbnailImage];
}];
}
At the bottom I have set the Image (that works) in a new property (prepareForSegueImage). NOW its loaded.
And now I've tried to pass only the prepareForSegueImage to the new view controller, but it actually doesn't pass the one from the cell, it passes the last one loaded in the whole table view from the first view controller.
I'm guessing:
[eventImage getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error)
{
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
pbdtvc.bookImageDetail = thumbnailImage;
}];
is an asynchronous request happening in the background, that will take some time to return. But your code is expecting it to happen instantly.
Load the image first and call the segue in the completion block,
EDIT
If it works in the first viewController (meaning you have the image) why are you requesting it again? why not simply pass the image you already have?
EDIT 2:
As explained in my comment, your variable is being overwritten each time the cellForRowAtindexPath is called. You could either wrap that code in an if statement, checking for an index or a certain image etc. or you can use the below code to get a specific cell and pull the image form that.
[tblView cellForRowAtIndexPath: [NSIndexPath indexPathForRow:2 inSection:0]];
If you have the image downloaded and have a relatively easy means of getting a reference to it you should not be downloading it again. This could cost the user on a 3G data plan as well as waste resources.
This happens because you are using the getDataInBackgroundWithBlock, which is an asynchronous call. As this happens in a background thread, it is probably not finished when you segue to the other viewcontroller.
You said it works fine in the first controller. I assume this means you have already downloaded the image. Put that in a property instead, and send this property to the next controller.
I'm currently using a plist to populate my table view rows(i.e. Name, Description and Image). When the user selects a row, a new controller is pushed up with an imageView presenting the rows image in full screen.
The problem that I'm facing is, passing the string to the new viewController's imageView.
All the NSLog's return the correct information, except that when it logs the UIImageView, it returns null then. Am I not connecting it correctly? The row doesn't display any image until it's selected (essentially the row is acting, similar to a thumbnail).
Any help would be greatly appreciated thank you!!!
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *childDictionary = [mainChildren objectAtIndex:indexPath.row];
//Image Name NSString from plist
childImage = [childDictionary objectForKey:#"Child Image"];
if ([childDictionary objectForKey:#"Child Image"] == nil) {
NSLog(#"No Image String Found.");
}
else {
NSLog(#"Image String Found. Image Name is: %#", childImage);
UIImage *myImage = [UIImage imageNamed:childImage];
NSLog(#"Image Found. Image is: %#", myImage);
UIImageView *childImageView = [childImageView setImage:myImage];
NSLog(#"ImageView Found. ImageView is: %#", childImageView);
FullscreenImageViewController *imgViewer = [[FullscreenImageViewController alloc] init];
imgViewer.fullScreenImageView = childImageView;
[self presentViewController:imgViewer animated:YES completion:nil];
}
}
When you instantiate a new UIImageView, it should be [[UIImageView alloc] initWithImage:image].
Or since your full screen image controller has property of image view, e.g. fullScreenImageView, you can just set the image of the property directly with a UIImage instance.
I have an odd problem. I am using an AQGridView which has a method similar to table view controller which I have defined as follows:
- (AQGridViewCell *)gridView:(AQGridView *)aGridView cellForItemAtIndex:(NSUInteger)index
{
static NSString *CellIdentifier = #"IssueCell";
AQGridViewCell *cell = (AQGridViewCell *)[gridView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:#"IssueCell" owner:self options:nil];
cell = [[AQGridViewCell alloc] initWithFrame:self.gridViewCellContent.frame
reuseIdentifier:CellIdentifier];
[cell.contentView addSubview:self.gridViewCellContent];
cell.selectionStyle = AQGridViewCellSelectionStyleNone;
}
IssueCell *content = (IssueCell *)[cell.contentView viewWithTag:1];
//This model object contains the title, picture, and date information
IssueModel *m = (IssueModel *)[self.issues objectAtIndex:index];
//If we have already downloaded the file, set the alpha to 1
if ([m hasPdfBeenDownloaded])
{
content.downloadIcon.hidden = YES;
content.imageView.alpha = 1;
content.progressView.hidden = YES;
}
else
{
if (m.pdfDownloadRequest && m.pdfDownloadRequest.isExecuting)
{
content.downloadIcon.hidden = YES;
content.imageView.alpha = .2;
content.progressView.hidden = NO;
}
else
{
content.downloadIcon.hidden = NO;
content.imageView.alpha = .2;
content.progressView.hidden = YES;
}
}
content.title.text = m.title;
// Only load cached images; defer new downloads until scrolling ends
if (!m.coverImageIcon)
{
if (self.gridView.dragging == NO && self.gridView.decelerating == NO)
{
[self startIconDownload:m forIndex:index];
}
content.imageView.image = [UIImage imageNamed:#"grid_cell_loading.png"];
}
else
{
content.imageView.image = m.coverImageIcon;
}
return cell;
}
My problem is since cells are reused, I lose the correct progress indication and updating of it. I am using ASIHTTP as follows:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:model.issuePdfUrl];
request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:ic, #"cell", model, #"model", nil];
model.pdfDownloadRequest = request;
[request setShouldContinueWhenAppEntersBackground:YES];
[request setDelegate:self];
[request setDownloadDestinationPath:mediaPath];
[request setDownloadProgressDelegate:ic.progressView];
[request startAsynchronous];
The problem I am having is when I scroll down and then scroll backup, I lose the progressView I used to have as a reusable cell is used.
What is the correct way to do this so I don't lose the progress view?
As far as I understand, you bind progressView to a cell (first one, for example), then you scroll to a second cell, it is being created. Then third. This third possibly reuses first cell. But progressBar is not recreated, you reuse it.
So you have one progressBar but two ASIHTTPRequests that point to it. That's not very good.
What can I suggest? Well. You can update link of downloadProgressDelegate with the progressBar during gridView:cellForItemAtIndex: call. That is more ok path. You also can remove reusability of cells. That might help but is less ok and can cause problems (for example memory leaks) in the future.
Another way is to make some single method that gets all the progress messages. And uses these messages to map progress data to a grid model.
I'm trying to keep my UITableView scrolling smoothly while going through about 700 pictures that are downloaded from the internet, cached (to internal storage) and displayed on each cell of the table. My code so far seems fine as far as scrolling performance. However, I noticed that sometimes, if the connection is being crappy or If I scroll really fast, a cell will display the wrong picture (that of another cell) for maybe about 1/2 a sec and then update to the image it is supposed to display.
I suspect 2 things so far:
A-
I might have a reentrancy issue from the point where my NSInvocationOperation calls back into the main thread with [self performSelectorOnMainThread:] to the point where the selector in the main thread gets executed. Though I don't really spot any shared variables.
B-
Some sort of race between the main thread and the NSInvocationOperation? Like:
1 main thread calls cacheImageFromURL
2 inside this call, UIImage spans the worker thread
3 worker thread is almost done and gets to call performSelectorOnMainThread
4 the cell in question is dequeued to be reused at this point, so main thread calls cahceImageFromURL again for a new image.
5 inside this call, UIImage stops the NSOPerationQueue which causes the previous NSInvocationOperation thread to die.
6 BUT, the thread had already called performSelectorOnMainThread
7 so the selector gets excited causing the old image to load.
8 immediately after this, the recently spawned thread is done fetching the new image and calls performSelectorOnMainThread again, causing the update to the right image.
If this is the case, I guess I'd need to set a flag on entry to the cacheImageFromURL method so that the worker thread code doesn't call performSelectorOnMainThread if there's another thread (the main one) already inside cacheImageFromURL?
Here's my code for my UIImageView subclass, which each cell in the table uses:
#implementation UIImageSmartView
//----------------------------------------------------------------------------------------------------------------------
#synthesize defaultNotFoundImagePath;
//----------------------------------------------------------------------------------------------------------------------
#pragma mark - init
//----------------------------------------------------------------------------------------------------------------------
- (void)dealloc
{
if(!opQueue)
{
[opQueue cancelAllOperations];
[opQueue release];
}
[super dealloc];
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark - functionality
//----------------------------------------------------------------------------------------------------------------------
- (bool)cacheImageFromURL:(NSString*)imageURL
{
/* If using for the first time, create the thread queue and keep it
around until the object goes out of scope*/
if(!opQueue)
opQueue = [[NSOperationQueue alloc] init];
else
[opQueue cancelAllOperations];
NSString *imageName = [[imageURL pathComponents] lastObject];
NSString* cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *cachedImagePath = [cachePath stringByAppendingPathComponent:imageName];
/* If the image is already cached, load it from the local cache dir.
Else span a thread and go get it from the internets.*/
if([[NSFileManager defaultManager] fileExistsAtPath:cachedImagePath])
[self setImage:[UIImage imageWithContentsOfFile:cachedImagePath]];
else
{
[self setImage:[UIImage imageWithContentsOfFile:self.defaultNotFoundImagePath]];
NSMutableArray *payload = [NSMutableArray arrayWithObjects:imageURL, cachedImagePath, nil];
/* Dispatch thread*/
concurrentOp = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(loadURI:) object:payload];
[opQueue addOperation: concurrentOp];
[concurrentOp release];
}
return YES;
}
//----------------------------------------------------------------------------------------------------------------------
/* Thread code*/
-(void)loadURI:(id)package
{
NSArray *payload = (NSArray*)package;
NSString *imageURL = [payload objectAtIndex:0];
NSString *cachedImagePath = [payload objectAtIndex:2];
/* Try fetching the image from the internets.
If we got it, write it to disk. If fail, set the path to the not found again.*/
UIImage *newThumbnail = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
if(!newThumbnail)
cachedImagePath = defaultNotFoundImagePath;
else
[UIImagePNGRepresentation(newThumbnail) writeToFile:cachedImagePath atomically:YES];
/* Call to the main thread - load the image from the cache directory
at this point it'll be the recently downloaded one or the NOT FOUND one.*/
[self performSelectorOnMainThread:#selector(updateImage:) withObject:cachedImagePath waitUntilDone:NO];
}
//----------------------------------------------------------------------------------------------------------------------
- (void)updateImage:(NSString*)cachedImagePath
{
[self setImage:[UIImage imageWithContentsOfFile:cachedImagePath]];
}
//----------------------------------------------------------------------------------------------------------------------
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
And the way this UIImage is used is in the context of cellForRowAtIndexPath, like so:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIImageSmartView *cachedImage;
// and some other stuff...
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleGray;
// some labels and tags stuff..
cachedImage = [[UIImageSmartView alloc] initWithFrame:CGRectMake(5, 5, 57, 80)];
cachedImage.contentMode = UIViewContentModeCenter;
cachedImage.defaultNotFoundImagePath = [[NSBundle mainBundle] pathForResource:#"DefaultNotFound" ofType:#"png"];
cachedImage.tag = PHOTO_TAG;
[cell.contentView addSubview:cachedImage];
[cell.contentView addSubview:mainLabel];
[cell.contentView addSubview:secondLabel];
}
else
{
cachedImage = (UIImageSmartView*)[cell.contentView viewWithTag:PHOTO_TAG];
mainLabel = (UILabel*)[cell.contentView viewWithTag:MAINLABEL_TAG];
}
// Configure the cell...
NSString *ImageName = [[[self.dbData objectAtIndex:indexPath.row] objectAtIndex:2]
stringByReplacingOccurrencesOfString:#".jpg"
withString:#"#57X80.png"];
NSString *imageURL = [NSString stringWithFormat:#"www.aServerAddress.com/%#/thumbnail5780/%#",
self.referencingTable,
ImageName];
[cachedImage cacheImageFromURL:imageURL];
mainLabel.text = [[self.dbData objectAtIndex:indexPath.row] objectAtIndex:0];
return cell;
}
The problem is reuse of cell, one cell makes the request of various images at same time, and is displaying when each one is downloaded, i know that you are canceling operations queue but as the processing caller is synchronous the operation continues the execution. I suggest try to save the indexPath of the request, and match it with the index path of the cell before set the UIImage.
D33pN16h7 is right in that the problem was cell reuse. However, instead of trying to make the indexPath thread-safe through an NSURLConnection, I decided to reimplement the whole thing by moving the NSOperationQueue into the UITableViewController code and having the concurrent imageView class be actually a proper subclass of NSOperation (since I was using NSOperationInvocation in the first place to try and avoid the full-fledged NSOperation subclass).
So now, the table controller manages it's own NSOperationQueue, the operations are subclasses of NSOperation and I can cancel them from the table controller code as the table view scrolls past them. And everything works fast and nice.