How do I keep the keyboard hidden when it's not wanted? - iphone

The app I'm working on allows the user both to read text and to compose text, using different buttons. My problem now is that on the screen for reading text, if the user taps inside the UITextView box used on the screen for writing text, the keyboard appears. The UITextView in this case is self.textView; I've put the keyboard notifications and the keyboardWillShow method inside if(self.textView) statements and then made sure to call [self.textView removeFromSuperView] and set self.textView = nil; at the beginning of the reading text methods, but the keyboard still appears when you tap the space where self.textView is set (programmatically, by the way, not using the IB).
What am I doing wrong?
Edit: Thanks for the answers, guys and gals, but still that darn keyboard keeps coming back, just like the cat in the song.... Here's my code. Forgive its length, please, if you can; if I've done something wonky I don't know where it is, and so I don't know what to leave out.
Here's viewDidLoad.
-(void)viewDidLoad {
[super viewDidLoad];
self.textView.editable=NO;
self.textView.userInteractionEnabled = NO;
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(previousHaiku)];
swipeRight.numberOfTouchesRequired = 1;
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipeRight];
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(nextHaiku)];
swipeLeft.numberOfTouchesRequired = 1;
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeLeft];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"gayHaiku.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"gayHaiku" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error];
}
self.gayHaiku = [[NSMutableArray alloc] initWithContentsOfFile: path];
[self nextHaiku];
}
Here's nextHaiku, the last method called in viewDidLoad -- this is the reading method.
-(void)nextHaiku
{
[self.view.layer removeAllAnimations];
[self.bar removeFromSuperview];
self.textToSave=#"";
self.haiku_text.text=#"";
[self.view viewWithTag:1].hidden = NO;
[self.view viewWithTag:3].hidden = NO;
int indexOfHaiku;
NSMutableArray *arrayOfHaikuSeen;
NSString *cat;
if (!self.selectedCategory) cat = #"Derfner";
else cat = self.selectedCategory;
NSArray *filteredArray;
if (cat==#"all")
{
filteredArray = self.gayHaiku;
indexOfHaiku = self.indxAll;
arrayOfHaikuSeen = self.theseAreDoneAll;
}
else
{
indexOfHaiku = (cat==#"user")?self.indxU:self.indxD;
arrayOfHaikuSeen = (cat==#"user")?self.theseAreDoneU:self.theseAreDoneD;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"category == %#", cat];
filteredArray = [self.gayHaiku filteredArrayUsingPredicate:predicate];
}
int array_tot = [filteredArray count];
int sortingHat;
NSString *txt;
if (array_tot > 0)
{
if (indexOfHaiku == arrayOfHaikuSeen.count)
{
while (true)
{
sortingHat = (arc4random() % array_tot);
if (![arrayOfHaikuSeen containsObject:[filteredArray objectAtIndex:sortingHat]]) break;
}
txt = [[filteredArray objectAtIndex:sortingHat] valueForKey:#"quote"];
if (!arrayOfHaikuSeen || arrayOfHaikuSeen.count==array_tot)
{
arrayOfHaikuSeen = [[NSMutableArray alloc] init];
}
[arrayOfHaikuSeen addObject:[filteredArray objectAtIndex:sortingHat]];
indexOfHaiku = arrayOfHaikuSeen.count;
if (arrayOfHaikuSeen.count==filteredArray.count)
{
[arrayOfHaikuSeen removeAllObjects];
indexOfHaiku=0;
}
}
else
{
txt = [[arrayOfHaikuSeen objectAtIndex:indexOfHaiku] valueForKey:#"quote"];
indexOfHaiku += 1;
}
}
//Need to test to make sure it starts over once all 110 haiku have been seen.
CGSize dimensions = CGSizeMake(320, 400);
CGSize xySize = [txt sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14.0] constrainedToSize:dimensions lineBreakMode:0];
self.haiku_text = [[UITextView alloc] initWithFrame:CGRectMake((320/2)-(xySize.width/2),200,320,200)];
self.haiku_text.font = [UIFont fontWithName:#"Helvetica Neue" size:14];
self.haiku_text.backgroundColor = [UIColor clearColor];
self.haiku_text.text=txt;
CATransition *transition = [CATransition animation];
transition.duration = 0.25;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype =kCATransitionFromRight;
transition.delegate = self;
[self.view.layer addAnimation:transition forKey:nil];
[self.view addSubview:self.haiku_text];
if (cat==#"user")
{
self.theseAreDoneU = arrayOfHaikuSeen;
self.indxU = indexOfHaiku;
}
else if (cat==#"all")
{
self.theseAreDoneAll = arrayOfHaikuSeen;
self.indxAll = indexOfHaiku;
}
else
{
self.theseAreDoneD = arrayOfHaikuSeen;
self.indxD = indexOfHaiku;
}
}
And here's the writing method.
-(void)userWritesHaiku
//Set up the screen.
[self clearScreen];
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 60, 280, 150)];
self.textView.delegate = self;
self.textView.returnKeyType = UIReturnKeyDefault;
self.textView.keyboardType = UIKeyboardTypeDefault;
self.textView.font = [UIFont fontWithName:#"Helvetica Neue" size:14];
self.textView.scrollEnabled = YES;
self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
self.textView.userInteractionEnabled = YES;
self.textView.editable=YES;
self.textView.backgroundColor = [UIColor colorWithRed:217 green:147 blue:182 alpha:.5];
[self.view addSubview: self.textView];
[self loadNavBar:#"Compose"];
[self addLeftButton:#"Instructions" callingMethod:#"haikuInstructions"];
//If you've added text before calling haikuInstructions, when you return from haikuInstructions the textView window with the different background color AND the keyboard.
[self addRightButton:#"Done" callingMethod:#"userFinishedWritingHaiku"];
self.titulus.hidesBackButton=YES;
[self seeNavBar];
//Create and add the space for user to write.
[self createSpaceToWrite];
if (self.textToSave!=#"")
{
self.textView.text = self.textToSave;
}
[self.view addSubview:self.textView];
[self.textView becomeFirstResponder];
//Keyboard notifications.
if (self.textView)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
}

try this
[self.textView setEditable:NO];

When the user taps on the reading button, I would just call
self.textView.userInteractionEnabled = NO;
and when you want them to edit it call
self.textView.userInteractionEnabled = YES;

Well, it turned out that the whole time there was a UITextView I'd created in the xib and forgotten about because it was hiding under the main view--when I decided to create the UITextView programmatically I didn't remember to delete the other one, because I couldn't see it, but it was there working its evil will the entire time. I finally figured this out after commenting out literally the entire code with the exception of [super viewDidLoad] and removing everything from the xib.

Related

ImageGallery image in black for ios 7

In my efforts to upgrade my application to support IOS7 I found out that ImageGallery don't load the images. in others iOS is ok.
In imageGalleryView:
- (void)initWithPhotos:(NSMutableArray *)photoURLStrings andCaptions:(NSArray *)myCaptions moveToPage:(int)page {
captions = [myCaptions copy];
photoUrls = [photoURLStrings copy];
NSLog(#"array---> %#", photoUrls);
photoLoaded = [[NSMutableArray alloc] init];
for (int i=0; i<[photoURLStrings count]; i++) {
[photoLoaded addObject:[NSNumber numberWithBool:FALSE]];
}
[pageControl setNumberOfPages:[photoUrls count]];
//scrollView= [[UIScrollView alloc] init];
scrollView.backgroundColor = [UIColor blackColor];
scrollView.pagingEnabled = TRUE;
scrollView.autoresizesSubviews = TRUE;
scrollView.contentSize = CGSizeMake(320 * [photoUrls count], scrollView.frame.size.height);
scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width*page, 0);
if (([captions objectAtIndex:page] == nil) || ([[captions objectAtIndex:page] isEqualToString:#""])) {
[textView setHidden:TRUE];
} else {
[textView setHidden:FALSE];
[textView setText:[captions objectAtIndex:page]];
}
[self showImages:page];}
- (void)showImages:(int)page {
AsyncImageViewController *asyncImageView;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
//NSLog(#"%#",[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]);
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
//NSLog(#"page:%i",page);
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
//[scrollView setBackgroundColor:[UIColor colorWithPatternImage:asyncImageView.image]];
[scrollView addSubview:asyncImageView];
[asyncImageView release];
}
}
page = page - 1;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
[scrollView addSubview:asyncImageView];
[asyncImageView release];
}
}
page = page + 2;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
[scrollView addSubview:asyncImageView];
//[scrollView setBackgroundColor:[UIColor colorWithPatternImage:asyncImageView.image]];
[asyncImageView release];}}}
In the asyncimageview:
- (void)loadImageFromURL:(NSURL*)url pos:(int) posicio {
if (connection!=nil) { [connection release]; }
if (data!=nil) { [data release]; }
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
loading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
if (posicio == 0) {
loading.center = CGPointMake(75/2,75/2);
}else {
loading.center = CGPointMake(160,210);
}
[loading startAnimating];
[self addSubview:loading];
[loading release];}//the URL connection calls this repeatedly as data arrives- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }
[data appendData:incrementalData];}//the URL connection calls this once all the data has downloaded- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
//so self data now has the complete image
[connection release];
connection=nil;
if ([[self subviews] count]>0) {
//then this must be another image, the old one is still in subviews
[[[self subviews] objectAtIndex:0] removeFromSuperview]; //so remove it (releases it also)
}//make an image view for the image
imageView = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
//make sizing choices based on your needs, experiment with these. maybe not all the calls below are needed.
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight );
//[self setBackgroundColor:[UIColor colorWithPatternImage:imageView]];
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout];
[self setNeedsLayout];
[loading stopAnimating];
[data release]; //don't need this any more, its in the UIImageView now
data=nil;}
//just in case you want to get the image directly, here it is in subviews- (UIImage*) image {
UIImageView* iv = [[self subviews] objectAtIndex:0];
return [iv image];}
I checked all and saw that it is UIView instead of UIImageView. probably Apple changed something. But xCode don't throw any errors.
Any idea how to fix it?

How we swipe more than 2 images in iOS horizontally?

i write the below code to swipe 2 images. it works fine
but now my task is to swipe more than 2 images horizontally.
and also at the last image if we swipe to the left the first image should appear
how can i achieve this?
-(void)viewDidLoad
{
[super viewDidLoad];
// instantiate gesture recognizer
UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:#selector(didSwipe:)];
[imageView addGestureRecognizer:rightSwipe];
UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:#selector(didSwipe:)];
leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
[imageView addGestureRecognizer:leftSwipe];
//setup images
image1 = [UIImage imageNamed:#"1.png"];
image2 = [UIImage imageNamed:#"2.png"];
imageView.image = image1;
}
-(void)didSwipe : (UISwipeGestureRecognizer *) sender
{
UISwipeGestureRecognizerDirection direction = sender.direction;
switch (direction) {
case UISwipeGestureRecognizerDirectionRight:
imageView.image = image2;
break;
case UISwipeGestureRecognizerDirectionLeft :
imageView.image = image1;
break;
default:
break;
}
}
Use below code and you will get desired output.
In the following code you app will use album photos and automatically sets size of the scrolling as per the number of images in album.
-(void)getAllPictures
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
NSMutableArray* assetURLDictionaries = [[NSMutableArray alloc] init];
library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != nil) {
if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
[assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
NSURL *url= (NSURL*) [[result defaultRepresentation]url];
[library assetForURL:url
resultBlock:^(ALAsset *asset) {
[mutableArray addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];
if ([mutableArray count]==count)
{
imageArray=[[NSArray alloc] initWithArray:mutableArray];
[self allPhotosCollected:imageArray];
}
}
failureBlock:^(NSError *error){ NSLog(#"operation was not successfull!"); } ];
}
}
};
NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
[assetGroups addObject:group];
count=[group numberOfAssets];
}
};
assetGroups = [[NSMutableArray alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {NSLog(#"There is an error");}];
}
-(void)allPhotosCollected:(NSArray*)imgArray
{
CGSize imageSize;
imageSize.width= imageView.bounds.size.width;
imageSize.height = imageView.bounds.size.height;
self.scrollView=[[UIScrollView alloc]init];
self.scrollView.frame = imageView.frame;
self.scrollView.contentSize = CGSizeMake(imageSize.width * imgArray.count, imageSize.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.bounces=YES;
self.scrollView.scrollEnabled = YES;
self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
[self.scrollView flashScrollIndicators];
[self.view addSubview:self.scrollView];
CGFloat xPos = 0.0;
for (UIImage *image in imgArray) {
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(xPos, 0.0, imageSize.width, imageSize.height);
[self.scrollView addSubview:imageView];
xPos += imageSize.width;
// assuming ARC, otherwise release imageView
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20,320 , 420)];
[self getAllPictures];
}
Store your multiple images in NSArray.
Now check condition for swipe right if yes than display image from that array.
and if swipe left than display previous image from that array..
Easy to use for loop and increment operator.
I hope you will get idea.

UIScrollView not updating and displaying properly

Im having problem in my UIscrollView,this is what I have done: Whenever a user picks an image (Multiple or Single) in camera roll thru a Imagepicker, I want to display it in my UIScrollView. I was able to display it, but when I go to the Imagepicker again then pick again an image,it doesnt update the UIScrollView, I tried putting my [self createScrollView] in my viewDidAppear but It recreates the UIScrollView but not update it, so the old images and new images are combined together. So I have put them in viewDidLoadbut It only update when I go to another View Controller then back again.
// My UIScrollView with thumbnail image
- (void) createScrollView {
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 300, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)];
[slotBg addSubview:self.scrollView];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView setContentSize:CGSizeMake(330, (row+1) * 60 + 10)];
}
// in my viewDidLoad
- (void)viewDidLoad
{
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
}
EDIT:
- (void) viewDidLoad {
[self createScrollView];
[_thumbs removeAllObjects];
UIView *removeView;
for(int i = 0; i < _thumbs.count; ++i) {
while((removeView = [scrollView viewWithTag:i]) != nil) {
[removeView removeFromSuperview];
}
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
}
}
There are two points:
Check for your data source. If image has been saved correctly in your documents directory or not.
No need to create scroll view and its parent view again. Move below code from createScrollView to viewDidLoad. these view should be created only once.
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 300, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)];
[slotBg addSubview:self.scrollView];
Now, from viewDidAppear, first update your _thumbs array (data source). Then call createScrollView function. Inside this function, first remove all the subviews using tag from UIScrollView. Add all the thumbs again as you have done. Then call [self setNeedsDisplay] before returning from createScrollView.

Save Text From UITextVIEW?

I'm having a problem : i can' find a way to save properly my UITextView in a NSString.
I have created 4 UITextViews and i want them to be saved in the same file.
Heres the code :
-(void)destinataireTextView {
self.destiView = [[[UITextView alloc] initWithFrame:CGRectMake(200, 160, 150, 120)] autorelease];
[self.view addSubview: self.destiView];
}
-(void)expediteurTextView {
self.expediView = [[[UITextView alloc] initWithFrame:CGRectMake(430, 200, 150, 120)] autorelease];
[self.view addSubview: self.expediView];
}
-(void)objetTextView {
self.objetView = [[[UITextView alloc] initWithFrame:CGRectMake(200, 295, 150, 120)] autorelease];
[self.view addSubview: self.objetView];
}
-(void)corpsTextView {
self.corpsView = [[[UITextView alloc] initWithFrame:CGRectMake(200, 335, 150, 120)] autorelease];
[self.view addSubview: self.corpsView];
}
-(void)viewDidLoad{
[super viewDidLoad];
[self destinataireTextView];
[self expediteurTextView];
[self objetTextView];
[self corpsTextView];
}
I've tried this piece of code :
-(void)viewDidLoad
[super viewDidLoad];
NSString *filePath = [self pathOfFile];
if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
desti.text = [array objectAtIndex:0];
[array release];
}
UIApplication *notif = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationWillTermite:) name:UIApplicationWillTerminateNotification object:notif];
}
-(NSString *) pathOfFile{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolder = [paths objectAtIndex:0];
return [documentFolder stringByAppendingFormat:#"SaveData.plist"];
}
-(void)applicationWillTermite:(NSNotification *)notification{
NSMutableArray *save = [[NSMutableArray alloc] init];
[save addObject:field1.text];
[save writeToFile:[self pathOfFile]atomically:YES];
[save release];
}
I desperately need help.
Thx
You don't really give us much to go on. No error messages. No suggestion of what you've tried or where it failed.
My guess, however, is this line:
return [documentFolder stringByAppendingFormat:#"SaveData.plist"];
I think you probably mean:
return [documentFolder stringByAppendingPathComponent:#"SaveData.plist"];
Otherwise your filename will look something like /some/pathSaveData.plist, which, obviously, is not valid.

iphone image is leaking, but where?

the image that is being displayed in this code is leaking but I cant figure out how. What I have a tableview that displays images to be displayed. Each time a user selects an image, it should remove the old image, download a new one, then add it to the scroll view. But the old image is not being released and I cant figure out why...
-(void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[imageView removeFromSuperview];
self.imageView = nil;
NSUInteger row = [indexPath row];
NSString *tempC = [[NSString alloc]initWithFormat:#"http://www.website.com/%#_0001.jpg",[pdfNamesFinalArray objectAtIndex:row] ];
chartFileName = tempC;
pdfName = [pdfNamesFinalArray objectAtIndex:row];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *tempString = [[[NSString alloc]initWithFormat:#"%#/%#.jpg",docsPath,pdfName]autorelease];
NSData *data = [NSData dataWithContentsOfFile:tempString];
if (data != NULL){
self.imageView = nil;
[imageView removeFromSuperview];
self.imageView = nil;
UIImageView *tempImage = [[[UIImageView alloc]initWithImage:[UIImage imageWithData:data]]autorelease];
self.imageView = tempImage;
[data release];
scrollView.contentSize = CGSizeMake(imageView.frame.size.width , imageView.frame.size.height);
scrollView.maximumZoomScale = 1;
scrollView.minimumZoomScale = .6;
scrollView.clipsToBounds = YES;
scrollView.delegate = self;
[scrollView addSubview:imageView];
scrollView.zoomScale = .37;
}
else {
[data release];
self.imageView = nil;
[imageView removeFromSuperview];
self.imageView = nil;
activityIndicator.hidden = NO;
getChartsButton.enabled = NO;
chartListButton.enabled = NO;
saveChartButton.enabled = NO;
[NSThread detachNewThreadSelector:#selector(downloadImages) toTarget:self withObject:nil];
}
chartPanel.hidden = YES;
}
-(void) downloadImages {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
self.imageView = nil;
[imageView removeFromSuperview];
NSURL *url = [[[NSURL alloc]initWithString:chartFileName]autorelease];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImageView *tempImage = [[[UIImageView alloc]initWithImage:[UIImage imageWithData:data]]autorelease];
self.imageView = tempImage;
tempImage = nil;
scrollView.contentSize = CGSizeMake(imageView.frame.size.width , imageView.frame.size.height);
scrollView.maximumZoomScale = 1;
scrollView.minimumZoomScale = .37;
scrollView.clipsToBounds = YES;
scrollView.delegate = self;
[scrollView addSubview:imageView];
scrollView.zoomScale = .6;
activityIndicator.hidden = YES;
getChartsButton.enabled = YES;
chartListButton.enabled = YES;
saveChartButton.enabled = YES;
[pool drain];
[pool release];
}
This looks wrong:
self.imageView = nil;
[imageView removeFromSuperview];
You are setting imageView to nil before removing it from the superview, so the 2nd statement is really just [nil removeFromSuperview];, which isn't going to do anything.
I think the leak is what David Gelhar said, but I just wanted to add that you shouldn't access UI stuff from threads other than the main thread (so for instance, don't do [imageView removeFromSuperview] under a separate thread). This can cause very odd problems, including mysterious leaks. Try putting all that stuff in a separate method on the main thread that you call with [self performSelectorOnMainThread:] and see if it still leaks.
Also (although this wouldn't cause the leak), [pool drain] releases the autorelease pool, so you shouldn't invoke [pool release] after it--it might release the pool on the main thread, possibly causing a crash somewhere down the line (since you could over-release the pool).