UIImageView memory Leak - ios

In my app, I am loading series of images to my UIImageView which has been created on init Method like
- (UIImage *)getImage:(int)currentIndex {
NSString *path = [self getImagePath:currentIndex];
[self.imageView setAccessibilityLabel:path];
path=[bundle pathForResource:path ofType:extension];
return [UIImage imageWithContentsOfFile:path] ;
}
- (void)changeImage:(int)currentIndex {
[self.imageView setImage:nil ];
[self.imageView setImage:[self getImage:currentIndex]];
}
But this code causes memory leaks .Something like
-malloc - 7KB - imageIO - png_malloc
i have tried "[[UIImage alloc ] initWithContentsOfFile]" with appropriate release calls but still no luck.
What am i missing on here.
Roughly whole class
- (id)initWithFrame:(CGRect)frame andBundle:(NSBundle *) bundleTobeInjected {
self = [super initWithFrame:frame];
if (self) {
// Initialization code.
self.opaque = YES;
bundle=bundleTobeInjected;
commonFunctions=[[Common alloc] init];
self.imageView = [[UIImageView alloc] initWithFrame:frame] ;
[self.imageView setImage:nil ];
self.imageView.contentMode = self.contentMode;
[self addSubview:imageView];
[self setAccessibilityEnabled];
}
return self;
}
-(void)setAccessibilityEnabled
{
self.imageView.isAccessibilityElement=true;
}
#pragma mark - Custom Logic
- (NSString *)getImagePath:(int)currentIndex {
NSString *path = [NSString stringWithFormat:#"%#%d%#", prefix,currentIndex,[commonFunctions imageNamedSmartForRotationSuffix]];
NSLog(#"%#", path);
return path;
}
- (UIImage *)getImage:(int)currentIndex {
NSString *path = [self getImagePath:currentIndex];
[self.imageView setAccessibilityLabel:path];
path=[bundle pathForResource:path ofType:extension];
return [UIImage imageWithContentsOfFile:path] ;
}
-(void)changeImage:(int)currentIndex {
[self.imageView setImage:nil ];
[self.imageView setImage:[self getImage:currentIndex]];
}
-(void)dealloc{
[extension release];
[prefix release];
[defaultImage release];
[image release];
[imageView release];
[commonFunctions release];
[super dealloc];
}

That code doesn't leak. Your leak is somewhere else :)
The leak is in the init method. Look at this line :
self.imageView = [[UIImageView alloc] initWithFrame:frame];
That line creates an image view that you own because you used an init method. You then assign that to your property which owns it again because I'm guessing your property is retain. You need to release the imageView after you've assigned it to your property, like this :
self.imageView = [[[UIImageView alloc] initWithFrame:frame] autorelease];
PS You don't need this line
[self.imageView setImage:nil ];

Related

How to add textfield in scrollview in ios?

I am making an app in which i am selecting photos from gallery and I want that on every picture or video one textfield will appear so that if i want to describe about that pic or video.
here is the code of display the photos but not showing the textfield on above the every pic in scrollview.
-(void)launchController
{
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc]initImagePicker];
elcPicker.maximumImagesCount = 100;
elcPicker.returnsOriginalImage = YES;
elcPicker.returnsImage = YES;
elcPicker.onOrder = YES;
elcPicker.mediaTypes = #[(NSString *)kUTTypeImage,(NSString *)kUTTypeMovie];
elcPicker.imagePickerDelegate = self;
[self presentViewController:elcPicker animated:YES completion:Nil];
}
-(void)launchSpecialController
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
self.specialLibrary = library;
NSMutableArray *groups = [NSMutableArray array];
[_specialLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group , BOOL *stop){
if(group){
[groups addObject:group];
}else{
[self displayPickerForGroup:[groups objectAtIndex:0]];
}
} failureBlock:^(NSError *error) {
chosenImages = nil;
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"Album Error: %# - %#", [error localizedDescription], [error localizedRecoverySuggestion]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
NSLog(#"A problem occured %#", [error description]);
// an error here mean
}];
}
- (void)displayPickerForGroup:(ALAssetsGroup *)group
{
ELCAssetTablePicker *tablePicker = [[ELCAssetTablePicker alloc] initWithStyle:UITableViewStylePlain];
tablePicker.singleSelection = YES;
tablePicker.immediateReturn = YES;
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:tablePicker];
elcPicker.maximumImagesCount = 1;
elcPicker.imagePickerDelegate = self;
elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
elcPicker.onOrder = NO; //For single image selection, do not display and return order of selected images
tablePicker.parent = elcPicker;
tablePicker.assetGroup = group;
[tablePicker.assetGroup setAssetsFilter:[ALAssetsFilter allAssets]];
[self presentViewController:elcPicker animated:YES completion:nil];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
return YES;
}else{
return toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}
}
#pragma mark ELCImageControllerDelegate Methods
-(void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
imageScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 150, self.view.frame.size.width, 450)];
[self.view addSubview:imageScroll];
UITextField *textfield1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 100, 100, 40)];
textfield1.backgroundColor = [UIColor greenColor];
NSMutableArray *textfieldArray = [NSMutableArray arrayWithCapacity:[info count]];
[textfieldArray addObject:textfield1];
textfield1.text= #"hello";
[imageScroll addSubview:textfield1];
for(UIView *v in [imageScroll subviews]){
[v removeFromSuperview];
}
CGRect workingFrame = imageScroll.frame;
workingFrame.origin.x = 0;
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
for (NSDictionary *dict in info) {
if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
[images addObject:image];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
[imageScroll addSubview:imageview];
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
} else {
NSLog(#"UIImagePickerControllerReferenceURL = %#", dict);
}
} else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo){
if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
[images addObject:image];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
[imageScroll addSubview:imageview];
;
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
} else {
NSLog(#"UIImagePickerControllerReferenceURL = %#", dict);
}
} else {
NSLog(#"Uknown asset type");
}
}
chosenImages = images;
[imageScroll setPagingEnabled:YES];
[imageScroll setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];
}
- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidLoad {
//chosenImages = [[NSArray alloc]init];
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
// textfield1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 100, 100, 40)];
// textfield1.backgroundColor = [UIColor greenColor];
// textfieldArray = [NSMutableArray arrayWithCapacity:[info count]];
// [textfieldArray addObject:textfield1];
// textfield1.text= #"hello";
// [imageScroll addSubview:textfield1];
UIButton *uploadimage = [[UIButton alloc]initWithFrame:CGRectMake(10, 30, 55, 55)];
uploadimage.backgroundColor = [UIColor blueColor];
[uploadimage setTitle:#"multiple images" forState:UIControlStateNormal];
[uploadimage addTarget:self action:#selector(launchSpecialController) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:uploadimage];
UIButton *singleimage = [[UIButton alloc]initWithFrame:CGRectMake(90, 30, 55, 55)];
singleimage.backgroundColor = [UIColor blueColor];
[singleimage setTitle:#"uploadimage" forState:UIControlStateNormal];
[singleimage addTarget:self action:#selector(launchController) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:singleimage];
imagePicker = [[UIImagePickerController alloc]init];
I don't understand your code lines. The problem should be there.
Why are you doing below things?
[imageScroll addSubview:textfield1];
for(UIView *v in [imageScroll subviews]){
[v removeFromSuperview];
}
In first line you are adding textfield to your scrollview and then you are using for loop to remove all subviews. It will remove your textfield from scrollview as well. You should not do this if you want to show textfield to user.
Please try by commenting the for loop. Hope it will work for you.
//Edit begins over here.
I think you should use UICollectionView instead of UIScrollView. In each and every cells of collectionview, you can show image and textfileds. It will be easy for you and also it will look better.
Thanks
Use NSMutableArray store UITextField value in it and call it with image array with function on the same button.
NSMutableArray *arr = [NSMutablearray....];
for (UIView *subV in self.view.subviews){
if([subV isKindOfClass:[UITextField class]])
{
//store it in a NSDictionary, so later can still know which
//textField your text belongs,
NSDictionary *tempDic = [NSDictionary dictionaryWithObjectAndKey:subV.txt
,subV.tag,/*or subVw.placeholder*/,nil];
[arr addObject:tempDic];
}
}

Memory continuously increase then app crash when i display image from document directory during scrolling UITableview

My Requirement is download all images in application memory and display it from local if its available.
Below is my code to access image from local and if its not available then it will download then display.
[cell.imgProfilePic processImageDataWithURLString:cData.PICTURE];
I have made custom UIImageView class
DImageView.h
#import <UIKit/UIKit.h>
#interface DImageView : UIImageView
#property (nonatomic, strong) UIActivityIndicatorView *activityView;
- (void)processImageDataWithURLString:(NSString *)urlString;
+ (UIImage *)getSavedImage :(NSString *)fileName;
#end
DImageView.m
#import "DImageView.h"
#define IMAGES_FOLDER_NAME #"DImages"
#implementation DImageView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{ }
return self;
}
- (void)dealloc
{
self.activityView = nil;
[super dealloc];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self initWithFrame:[self frame]];
}
return self;
}
- (void)processImageDataWithURLString:(NSString *)urlString
{
#autoreleasepool
{
UIImage * saveImg =[DImageView getSavedImage:urlString];
if (saveImg)
{
#autoreleasepool
{
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_async(callerQueue, ^{
#autoreleasepool{
[self setImage:saveImg];
}
});
}
}
else
{
[self showActivityIndicator];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_queue_t downloadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);
__block NSError* error = nil;
dispatch_async(downloadQueue, ^{
#autoreleasepool
{
NSData * imageData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
if (!error)
{
dispatch_async(callerQueue, ^{
#autoreleasepool {
UIImage *image = [UIImage imageWithData:imageData];
[self setImage:image];
[self hideActivityIndicator];
[self saveImageWithFolderName:IMAGES_FOLDER_NAME AndFileName:urlString AndImage:imageData];
}
});
}
}
});
dispatch_release(downloadQueue);
}
}
}
- (void) showActivityIndicator
{
self.activityView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
self.activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
self.activityView.hidesWhenStopped = TRUE;
self.activityView.backgroundColor = [UIColor clearColor];
self.activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
[self addSubview:self.activityView];
[self.activityView startAnimating];
}
- (void) hideActivityIndicator
{
CAAnimation *animation = [NSClassFromString(#"CATransition") animation];
[animation setValue:#"kCATransitionFade" forKey:#"type"];
animation.duration = 0.4;;
[self.layer addAnimation:animation forKey:nil];
[self.activityView stopAnimating];
[self.activityView removeFromSuperview];
for (UIView * view in self.subviews)
{
if([view isKindOfClass:[UIActivityIndicatorView class]])
[view removeFromSuperview];
}
}
- (void)saveImageWithFolderName:(NSString *)folderName AndFileName:(NSString *)fileName AndImage:(NSData *) imageData
{
#autoreleasepool{
NSFileManager *fileManger = [[NSFileManager defaultManager] autorelease];
NSString *directoryPath = [[NSString stringWithFormat:#"%#/%#",[DImageView applicationDocumentsDirectory],folderName] autorelease];
if (![fileManger fileExistsAtPath:directoryPath])
{
NSError *error = nil;
[fileManger createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
}
fileName = [DImageView fileNameValidate:fileName];
NSString *filePath = [[NSString stringWithFormat:#"%#/%#",directoryPath,fileName] autorelease];
BOOL isSaved = [imageData writeToFile:filePath atomically:YES];
if (!isSaved)DLog(#" ** Img Not Saved");
}
}
+ (NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
+ (UIImage *)getSavedImage :(NSString *)fileName
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
fileName = [DImageView fileNameValidate:fileName];
NSFileManager * fileManger = [[NSFileManager defaultManager] autorelease];
NSString * directoryPath = [[NSString stringWithFormat:#"%#/%#",[DImageView applicationDocumentsDirectory],IMAGES_FOLDER_NAME] autorelease];
NSString * filePath = [[NSString stringWithFormat:#"%#/%#",directoryPath,fileName] autorelease];
if ([fileManger fileExistsAtPath:directoryPath])
{
UIImage *image = [[[UIImage imageWithContentsOfFile:filePath] retain]autorelease];
if (image)
return image;
else
return nil;
}
[pool release];
return nil;
}
+ (NSString*) fileNameValidate : (NSString*) name
{
name = [name stringByReplacingOccurrencesOfString:#"://" withString:#"##"];
name = [name stringByReplacingOccurrencesOfString:#"/" withString:#"#"];
name = [name stringByReplacingOccurrencesOfString:#"%20" withString:#""];
return name;
}
#end
Everything is working fine with smooth scrolling as well as asyncImage download in background.
The issue is when i scroll UITableview application memory is continuously increase and after some time i got Receive memory waring 2/3 time then application crash.
When i use AsyncImageView class that time memory not increase and its working fine. But due to app requirement i saved all images to Document Directory and display from it if its available.
i have tried with #autoreleasepool and release some variable but not getting success.
I appreciated if any one have the solution to manage memory management.
**ARC is off in my application.**
It's possible that UIImagePNGRepresentation returns non-autoreleased object - you can try to release it and see if that results in a crash. Obviously you are not releasing something, but nothing other than the image representation appears obvious.
A few other comments:
run your app in Instruments, using the ObjectAlloc tool, and it should be immediately obvious what objects are not dealloced. If you don't know Instruments, well, its time now to learn it.
you can 'track' objects and get a message when they are dealloced using ObjectTracker - however it was designed for ARC so you may need to tweak it. If you use it you would see a message when each of your objects are dealloced
when the table view is done with a cell, there is a delegate method that you can receive that tells you so, and you can then nil (release) and objects the cell retains
your use of downloadQueue is bizarre - create it once in your instance as an ivar, use it as you need, and in dealloc release it
you hide the activity spinner on the main queue, but don't start it on the main queue
you command the activity view to remove itself from its superview, but then look for in in the subviews and try to remove it there:
[self.activityView removeFromSuperview];
for (UIView * view in self.subviews)
{
if([view isKindOfClass:[UIActivityIndicatorView class]])
[view removeFromSuperview];
}
In the end, Instruments is what you want. You can read up more about it here, or just google and you will surely find a slew of blogs to read.
Yes Finally i have resolved it.
The code which is in Question is working fine now. but Without release some objects and #autoreleasepool block which is in code, memory was increase continuously during scroll UITableView.
From the Instrument i found that memory increase in UILableView and UIImageView. I am using Custom UITableViewCell and in that file i havnt implement dealloc method. So When i have implement dealloc method in UITableViewCell .m file and release & nil all object.
After that memory not increase during scroll TableView and its Resolved the issue.
As per my Understanding there is an issue in your "getSavedImage" Method you have to manage memory Manually instead of 'autorelease' so as My suggestion is use
UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath]
and also release it after use of it. means after '[self setImage:saveImg];'
[saveImg release]
instead of this.
[[UIImage imageWithContentsOfFile:filePath] retain];
'Don't Use Autorelease because it has staying in memory until pool not drain' and just because of this you got an memory issue.

How to show a image from a url and load it into a UIImageView

I need to load a image from a URL into a UIImageView. Each time the URL would be different because i am JSON parsing a website. I am able to get the URL. However when i run the app, there is no image in the UIImageView.
This is my code
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
if ([eventNameDesc containsString:#"src="]) {
eventNameDesc = #"";
}
else {
eventDescription.text = eventNameDesc;
}
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:#selector(shareButtonPressed)];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)shareButtonPressed {
NSString *shareText = eventNameDesc;
NSArray *itemsToShare = #[shareText];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:itemsToShare applicationActivities:nil];
activityVC.excludedActivityTypes = #[];
[self presentViewController:activityVC animated:YES completion:nil];
}
- (void)loadImage {
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:self.imageURL]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
[self performSelectorOnMainThread:#selector(displayImage:) withObject:image waitUntilDone:NO];
}
- (void)displayImage:(UIImage *)image {
[self.ImageView setImage:image]; //UIImageView
}
#end
What is wrong with my code? Somebody please help.
You can make a UIImage object using the code provided here
After that you can add your UIImage object to any UIImageView object.
This is the code that works for me.
UIImage *anImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://4.bp.blogspot.com/-K7vl-ShXrNc/VQU-D0NTFgI/AAAAAAAAAOg/aBIUOwF2nEQ/s1600/contact.png"]]];
UIImageView *temp = [[UIImageView alloc] initWithImage:anImage];
[self.view addSubview:temp];
Here is a screenshot.

Loading overlay on collection view

I have a loading view that I insert over the top of a view while it is parsing data from the internet using a separate thread, in this case its on top of a UICollectionView.
For some reason that I cannot understand the loading overlay disappears on its own whist the parsing is still taking place, presenting a blank screen for a second or two. It doesn't seem to happen on UITableViews just on UIcollectionviews. Any help would be appreciated.
Activity overlay.m:
#import "ActivityOverlayController.h
#interface ActivityOverlayController ()
#end
#implementation ActivityOverlayController
-(id)initWithFrame:(CGRect)theFrame {
if (self = [super init]) {
frame = theFrame;
self.view.frame = theFrame;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"%#", #"ActivityOverlayController called");
container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 30)];
activityLabel = [[UILabel alloc] init];
activityLabel.text = NSLocalizedString(#"Loading", #"string1");
activityLabel.textColor = [UIColor lightGrayColor];
activityLabel.font = [UIFont boldSystemFontOfSize:17];
[container addSubview:activityLabel];
activityLabel.frame = CGRectMake(0, 3, 70, 25);
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.color = [UIColor blackColor];
activityIndicator.hidesWhenStopped = TRUE;
[activityIndicator startAnimating];
activityIndicator.frame = CGRectMake(80, 0, 30, 30);
[container addSubview:activityIndicator];
[self.view addSubview:container];
container.center = CGPointMake(frame.size.width/2, frame.size.height/2);
self.view.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:0.7];
}
-(void)viewWillAppear:(BOOL) animated {
[super viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL) animated {
[super viewWillDisappear:animated];
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[activityIndicator stopAnimating];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
Parsing part of collectionViewController.m:
-(void)ParseCollectionView{
[self performSelectorOnMainThread:#selector(showActivityView) withObject:nil waitUntilDone:YES];
CollectionViewImages = [[NSMutableArray alloc]init];
NSData *xmlData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:GalleryTitle]];
cvTBXML = [[TBXML alloc]initWithXMLData:xmlData];
// Obtain root element
TBXMLElement * root = cvTBXML.rootXMLElement;
TBXMLElement * channel = [TBXML childElementNamed:#"channel" parentElement:root];
if (root)
{
TBXMLElement * item = [TBXML childElementNamed:#"item" parentElement:channel];
while (item !=nil)
{
//create new instance of news object
NSObject *Imagetoparse = [[GalleryImage alloc] init];
TBXMLElement * link = [TBXML childElementNamed:#"link" parentElement:item];
NSString *linktext= [TBXML textForElement:link];
[Imagetoparse setValue:linktext forKey:#"link"];
TBXMLElement * thumbnail = [TBXML childElementNamed:#"description" parentElement:item];
NSString *Thumbnailtext= [TBXML textForElement:thumbnail];
Thumbnailtext = [Thumbnailtext substringFromIndex:21];
NSInteger *slength = Thumbnailtext.length -4;
Thumbnailtext = [Thumbnailtext substringToIndex:slength];
Thumbnailtext = [Thumbnailtext stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
Thumbnailtext = [Thumbnailtext stringByReplacingOccurrencesOfString:#"thumb" withString:#"main"];
NSLog(#"Thumnail1 : %#", Thumbnailtext);
NSData *Thumbnailimage = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: Thumbnailtext]];
[Imagetoparse setValue:Thumbnailimage forKey:#"thumbnail"];
[CollectionViewImages addObject:Imagetoparse];
item = [TBXML nextSiblingNamed:#"item" searchFromElement:item];
}
}
[self.collectionView reloadData];
NSLog(#"%#", #"Finished Parse Collection View");
[self performSelectorOnMainThread:#selector(hideActivityView) withObject:nil waitUntilDone:NO];
}
-(void)showActivityView {
if (overlayController == nil) {
overlayController = [[ActivityOverlayController alloc] initWithFrame:(self.view.superview.bounds)];
}
[self.view.superview insertSubview:overlayController.view aboveSubview:self.view];
}
-(void)hideActivityView {
[overlayController.view removeFromSuperview];
}

How do I use a for loop to display NSArray of UIImage's

Hey guys,
So.... lets say I have an NSArray of images
NSMutableArray *images = [NSMutableArray new];
[images addObject:[UIImage imageNamed:#"line1.png"]];
[images addObject:[UIImage imageNamed:#"line2.png"]];
[images addObject:[UIImage imageNamed:#"line3.png"]];
[images addObject:[UIImage imageNamed:#"line4.png"]];
Now I would like to load all these at once using a for loop but here is the catch.... I need to be able to set the images as hidden until the user unhides through interaction.
for (UIImage *image in images) {
UIImageView *line = [[UIImageView alloc] initWithImage:image];
line.hidden = YES;
[self.view addSubview:line];
}
But then how to I set the hidden BOOL to NO using another method?
As a secondary question, how would one release *line in the code above?
Thanks,
Darren
One option is to set up your images like:
int nextTag = 1;
for (UIImage *image in images) {
UIImageView *line = [[UIImageView alloc] initWithImage:image];
line.hidden = YES;
line.tag = nextTag;
[self.view addSubview:line];
[line release];
nextTag++;
}
...and then to unhide them you can do:
UIView* imageView = [self.view viewWithTag: lineNumber];
imageView.hidden = NO;
...assuming that your user-interaction handler is able to determine what line in the UI the user is interacting with.
As a secondary question, how would one release *line in the code above?
for (UIImage *image in images) {
UIImageView *line = [[UIImageView alloc] initWithImage:image];
line.hidden = YES;
[self.view addSubview:line]; // this retains the subview.
[line release]; // release line like this.
}
**
-(IBAction)btnReviewStar:(id)sender{
for (int i =([sender tag] ==30); i<36; i++) {
btnReviewStar.selected = NO;
btnReviewStar1.selected = NO;
btnReviewStar2.selected = NO;
btnReviewStar3.selected = NO;
btnReviewStar4.selected = NO;
if([sender tag] == 31) {
btnReviewStar.selected = YES;
break;
} else if([sender tag]==32) {
btnReviewStar.selected = YES;
btnReviewStar1.selected = YES;
break;
} else if([sender tag]==33) {
btnReviewStar.selected = YES;
btnReviewStar1.selected = YES;
btnReviewStar2.selected = YES;
break;
} else if([sender tag]==34) {
btnReviewStar.selected = YES;
btnReviewStar1.selected = YES;
btnReviewStar2.selected = YES;
btnReviewStar3.selected = YES;
break;
} else {
btnReviewStar.selected = YES;
btnReviewStar1.selected = YES;
btnReviewStar2.selected = YES;
btnReviewStar3.selected = YES;
btnReviewStar4.selected = YES;
break;
}
}
}
**

Resources