Hope you can help me with this.
I have an app that needs to show one of two maps via the setting of a UISwitch. The settings.bundle is all set up and I am trying to write an If statement to determine if the switch is on or off, and to display the right image.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL Enabled = [defaults boolForKey:#"zones_preference"];
if (Enabled == #"Enabled") {
[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"withzones.jpg"]];
}
else {
[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"withoutzones.jpg"]];
}
This builds without error, but doesn't load the image into the ScrollView. Could anyone advise on where I am going wrong?
Well, the code you've posted only creates a UIImageView object and doesn't do anything more. It's a leak too.
There's one more error in the line
if (Enabled == #"Enabled") {
Here, you are comparing a boolean to a string which will evaluate to false automatically so it needs to be corrected too.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL enabled = [defaults boolForKey:#"zones_preference"];
UIImageView * imageView;
if ( enabled ) {
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"withzones.jpg"]];
} else {
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"withoutzones.jpg"]];
}
imageView.frame = imageViewFrame; // Where "imageViewFrame" is an appropriate frame.
[scrollView addSubview:imageView];
[imageView release];
Deepak, that was very useful and thank you. I had been working with a variable, but the mistake I had made was that I was trying to add the setup of the variable in with the creation of the UIImageView.
I'll work with this and see how I get on.
Related
I am currently working on a UICollectionView with a lot of images. However, it sometimes crashes in this view with memory warning. I am using AFNetworking and UIImageView+AFNetworking category to set image through setImageWithURL: method. One issue can be caching. I am not sure if AFNetworking deals with image caching. Anyway, is there a way to optimize this code in terms of memory management? Or if I am to implement didReceiveMemoryWarning method in this view controller, what can be put in this method? I attach the code for cellForItemAtIndexPath for this collection view.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"RecipeCell" forIndexPath:indexPath];
// setting the image view for the cell using AFNetworking. Does this do caching automatically?
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:6];
if (PRODUCTION) {
[recipeImageView setImageWithURL:[[self.recipes objectAtIndex:indexPath.row] objectForKey:#"recipe_image"] placeholderImage:[UIImage imageNamed:#"default_recipe_picture.png"]];
} else {
[recipeImageView setImageWithURL:[NSString stringWithFormat:#"http://localhost:5000/%#", [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"recipe_image"]] placeholderImage:[UIImage imageNamed:#"default_recipe_picture.png"]];
}
// configure the back of the cell. fill all the info.
UITextView *recipeNameView = (UITextView *)[cell viewWithTag:8];
recipeNameView.text = [NSString stringWithFormat:#"%#", [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"recipe_name"]];
UILabel *recipeNameLabel = (UILabel *)[cell viewWithTag:2];
recipeNameLabel.text = [NSString stringWithFormat:#"%#", [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"recipe_name"]];
NSDictionary *user = [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"user"];
UIButton *chefNameButton = (UIButton *)[cell viewWithTag:3];
[chefNameButton setTitle:[NSString stringWithFormat:#"%# %#", [user objectForKey:#"first_name"], [user objectForKey:#"last_name"]] forState:UIControlStateNormal];
NSMutableArray *missingIngredientsStringArray = [[NSMutableArray alloc] init];
NSArray *missingIngredients = [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"missing_ingredients"];
for (NSDictionary *missingIngredient in missingIngredients) {
[missingIngredientsStringArray addObject:[missingIngredient objectForKey:#"name"]];
}
NSString *missingIngredientsString = [missingIngredientsStringArray componentsJoinedByString:#","];
UITextView *missingIngredientsView = (UITextView *)[cell viewWithTag:4];
missingIngredientsView.text = [NSString stringWithFormat:#"%u Missing Ingredients: %#", missingIngredients.count, missingIngredientsString];
// configure the front of the cell. chef name button and missing ingredients and likes on front view
UIButton *frontNameButton = (UIButton *)[cell viewWithTag:11];
[frontNameButton setTitle:[NSString stringWithFormat:#"%# %#", [user objectForKey:#"first_name"], [user objectForKey:#"last_name"]] forState:UIControlStateNormal];
[frontNameButton sizeToFit];
frontNameButton.frame = CGRectMake(160 - [frontNameButton.titleLabel.text sizeWithFont:[UIFont boldSystemFontOfSize:13]].width - 7, frontNameButton.frame.origin.y, frontNameButton.frame.size.width, frontNameButton.frame.size.height);
UILabel *likesLabel = (UILabel *)[cell viewWithTag:9];
likesLabel.text = [NSString stringWithFormat:#"%# likes", [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"likes"]];
UIButton *missingIngredientsButton = (UIButton *)[cell viewWithTag:12];
[missingIngredientsButton setBackgroundImage:[UIImage imageNamed:#"badge_green.png"] forState:UIControlStateSelected];
if (missingIngredients.count == 0) {
missingIngredientsButton.selected = YES;
[missingIngredientsButton setTitle:#"" forState:UIControlStateNormal];
} else {
missingIngredientsButton.selected = NO;
[missingIngredientsButton setTitle:[NSString stringWithFormat:#"%u", missingIngredients.count] forState:UIControlStateNormal];
}
// make back view invisible.
UIView *backView = [cell viewWithTag:1];
UIView *frontView = [cell viewWithTag:5];
frontView.alpha = 1.0;
backView.alpha = 0;
// adding flip gesture recognizers
UIView *flipView1 = [cell viewWithTag:12];
UIView *flipView2 = [cell viewWithTag:1];
UITapGestureRecognizer *flipGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(flipCell:)];
UITapGestureRecognizer *flipGestureRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(flipCell:)];
[flipView1 addGestureRecognizer:flipGestureRecognizer1];
[flipView2 addGestureRecognizer:flipGestureRecognizer2];
return cell;
}
[Edit] I attach a screenshot of my Instruments run.
You can see that memory allocation increases as I just push segue and press back button repeatedly. Things that just keep increasing are CFData, CALayer, CABackingStore, UITableView. I doubt these are things that are created after segue, and they are not being released... Please help!
You're probably going to want some sort of image caching strategy to avoid re-downloading images. And UIImageView+AFNetworking category does cache images for you. But you may also have the responses being cached in the in-memory URL cache, which in this case is somewhat redundant.
So you might consider reducing or turning off the in-memory URL cache. I had the issue you're describing and the following reduced my memory issues quite a bit:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
AFNetworking automatically stores images in an NSCache collection, which automatically removes some or all of the images from memory on a low memory warning. AFNetworking is probably not your issue.
In fact, I don't think displaying images is your issue unless you're downloading lots of very large images and displaying them simultaneously. (If this is the case, you should try optimizing your images for display on the device so they don't need to be resized.)
One issue I see is that you are adding a gesture recognizer to the cell every time it comes into the view, but cells are reused, so when a cell comes in again you are adding unnecessary gesture recognizers to it. You could resolve this by subclassing UITableViewCell and assigning the gesture recognizers as properties. You could also resolve this by checking flipView1 and flipView2 to see if they have gesture recognizers attached before adding them. (I'm not sure if this is enough to cause a memory warning though.)
I'd recommend going to Build -> Profile and selecting the Allocations instrument. On the left, select Objective C only, and hide system calls. Then, scroll through your collection view and look at the instrument to see what's taking up all the memory.
UPDATE
Here's a screenshot of the Allocations tool:
In my app, the user can save an image to their documents directory. At launch, I grab the image, add a border, and put it into a UIImageview like this....
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/ImageOne.jpg", docDirectory];
UIImage *unborderedImage = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];
//image found....add border
UIImage *imageWithBorder = [self addBorderToImage:unborderedImage];
imageOneView.image = imageWithBorder;
Ideally, I like to check that the image is there first before adding a border. If not, load an "image not available" placeholder. Something like this:
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/ImageOne.jpg", docDirectory];
UIImage *unborderedImage = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];
NSError * error;
if (error != nil) {
//image found....add border
UIImage *imageWithBorder = [self addBorderToImage:unborderedImage];
imageOneView.image = imageWithBorder;
} else
//no image saved
[imageOneView setImage:[UIImage imageNamed:#"photoNotAvailable.png"]];
}
Of course, this doesn't work. I just can't seem to figure out how handle if "ImageOne.jpg" isn't found.
As it turns out, I need to do other things with the image elsewhere within the app. This would also depend on whether or not the user had saved an image or not. So in my method where the user can save the image, I send out a NSNotification that the image has changed. Then on my MainView, I look for the notification and key off that.
When saved:
[collectionOneUserDefinedDefaults setObject:#"image added" forKey:#"collectionOneImageAdded"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"collectionOneImageChanged" object:self];
Then in my MainView I look for the notification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(updateCollectionOneImage) name:#"collectionOneImageChanged" object:nil];
- (void)updateCollectionOneImage {
//check if an image was ever saved, if so, replace the noPhotoAvailalble placeholder
NSUserDefaults *collectionOneUserDefinedDefaults = [NSUserDefaults standardUserDefaults];
NSString *collectionOneImageTextString = [collectionOneUserDefinedDefaults stringForKey:#"collectionOneImageAdded"];
if (collectionOneImageTextString == nil || [collectionOneImageTextString isEqualToString:#""]) {
[collectionOneImage setImage:[UIImage imageNamed:#"photoNotAvailable.png"]];
}
else {
//pull in collection one image from the Documents folder
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/CollectionOneImage.jpg", docDirectory];
UIImage *unborderedImage = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];
//image found....add border
UIImage *imageWithBorder = [self addBorderToImage:unborderedImage];
collectionOneImage.image = imageWithBorder;
}
}
It works perfectly. It in turn builds in the error handling. If the user saved and image, it gets loaded. If not, a placeholder image is loaded.
Your error handling here is doing nothing and is misguided. All you need do is simply check if unborderedImage is nil or not.
I've been struggling with this for quite a few days now; my app has a diagram with uitextfields to represent labelling of the picture. I would like to check the user input against a dictionary (for the answer) and if it is correct, increase the score by 1.
I had it working by 'hard coding' each of the textfield.text queries each with their own if statement, but I would like a better and more reusable way if possible?
I've tried this so far:
- (IBAction)checkAnswers:(UITextField *)textField
{
// array for each textfield
allTextfields = [[NSArray alloc] initWithObjects:eyepiece, objectiveLenses, focussingKnobs, stage, mirror, nil];
// array for each UIImageView
allTicks = [[NSArray alloc] initWithObjects:eyepieceTick, objectiveTick, focussingTick, stageTick, mirrorTick, nil];
UIImage *image = [UIImage imageNamed:#"Tick.png"];
for (textField in allTextfields) {
if ([textField.text isEqualToString:[[microscopeBrain.microscopeDictionary valueForKey:theTextfieldTag] valueForKey:#"Answer"]]) {
[[allTicks objectAtIndex:textField.tag] setImage:image];
x++;
textField.enabled = NO;
NSLog(#"%#", microscopeBrain.microscopeDictionary);
// NSLog(#"%#", [[microscopeBrain.microscopeDictionary valueForKey:theTextfieldTag] valueForKey:#"Answer"]);
}
finalMicroscopeScore = [[NSString alloc] initWithFormat:#"%i", x];
microscopeScoreLabel.text = [[NSString alloc] initWithFormat:#"%i", x];
}
}
The problem is that even if the answers are in the wrong textfield, as long as one is correct, they will all show up as right, which is kind of embarrassing!
Any help would be very much appreciated.
Try changing the valueForKey:theTextFieldTag to valueForKey:textField.tag and see if that helps. You don't show how you get the value for theTextFieldTag, so I'm not sure if that's the problem.
hi am doing an iphone twitter app with json and i am wondering if it is possible to set the
cell.accessoryType to a image in UITableView? or possible move the image to the right hand side...any clues?
Sure. Just use the accessoryView property of UITableViewCell and assign a UIImageView:
UIImage *image = [UIImage imageNamed:#"fileNameOfYourImage.jpg"]; //or wherever you take your image from
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
cell.accessoryView = imageView;
[imageView release];
No need to use imageview, just provide this for simple arrow.
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
i have an uibarbuttonitem, but i was initialize it using initwithcustomview. I want to change it backgrounds using an image, but i dont know how to do. I was using setBackground method, like this
NSArray *segmentText = [segmentTextMutable copy];
UIImage *image = [[[UIImage alloc] init] autorelease];
image = [UIImage imageNamed:#"bunga.jpg"];
_docSegmentedControl = [[UISegmentedControl alloc] initWithItems:segmentText];
_docSegmentedControl.autoresizingMask = UIViewAutoresizingFlexibleHeight;
_docSegmentedControl.segmentedControlStyle = UISegmentedControlStyleBezeled;
[_docSegmentedControl addTarget:self action:#selector(docSegmentAction:) forControlEvents:UIControlEventValueChanged];
[_docSegmentedControl setBackgroundColor:[UIColor colorWithPatternImage:image]];
but the uibarbuttonitem still not show the image, it's just change the segmented control background, not the barbutton.
Can somebody help me?
Perhaps you want to change the tint-color (#property(nonatomic, retain) UIColor *tintColor) because UISegmentedControl has no background-color (just because it inherits it from UIView does not mean it uses it though)