Would like to keep cache data when changing to other UIView - iphone

i would love to have some help or any keyword that i can use to search for.
My problem is I have one UIView, called "UpdateViewController.xib" that load 20 small images and text below those images by programmatically.
and when user click on those images it will change to next view that i created by IB, called "imageSumVuew.xib" and i have a button to link back to UpdateViewController.
#import "imageSumView.h" // next view that i wanna load//
// the transition to next view
imageSumView *nextView = [[imageSumView alloc]init];
self.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:nextView animated:YES completion:NULL];
[nextView release];
in the nextView i have code similar to this which come back to this view
#import "UpdateViewController.h" // old that i wanna load back//
// the transition to old view
UpdateViewController *oldView = [[UpdateViewController alloc]init];
self.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:oldView animated:YES completion:NULL];
[oldView release];
the problem is when it did load back to UpdateViewController, all my images and text has to reload all over again.
The question is " how can i keep cache of the UpdateViewController view?", i don't want user to reload images all over again because they have to go back and forth between this page for several times to see which image that they wanna pick.
Think of Instragram that you see list of your friends images then you wanna check your first friends's photo and after that you come back to overall image of your friends without loading and choose second friends.

Store image data with unique id to temporary directory once it is downloaded for the first time. For the next time check for that user id's image in your directory, if it is there then load image from there. For example :
#define TMP NSTemporaryDirectory()
NSString *filename=[NSMutableString stringWithFormat:#"userimage_%#",userId];
NSString *uniquePath = [TMP stringByAppendingPathComponent:filename];
NSData *dataImage = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]
UIImage *image = [[UIImage alloc] initWithData: dataImage];
[UIImageJPEGRepresentation(image, 1.0f) writeToFile: uniquePath atomically: YES];
[image release];
To get ur image you can do something like below:
- (NSData *) getImage: (NSString *)userId
{
NSString *filename=[NSMutableString stringWithFormat:#"userimage_%#,userId];
NSString *uniquePath = [TMP stringByAppendingPathComponent: filename];
if([[NSFileManager defaultManager] fileExistsAtPath: uniquePath])
{
return [[NSData alloc] initWithContentsOfFile:uniquePath];
}
return nil;
}

Related

Multiple NSThreads running simultaneously causing app freezes

I am developing an application in which I have a display a lot of images in my table view.These images has to come from server, so I have create another thread in which the image get processed and then set on table view cell to make our table view scrolls smoothly and properly.
My problem is when I scrolls my table view to a number of times, the app get freezes and after some time the xcode shows the message shown in below image:-
My table view cell code :-
id object = [imageDictFunctionApp objectForKey:[NSString stringWithFormat:#"%d",functionAppButton.tag]];
if(!object){
NSArray *catdictObject=[NSArray arrayWithObjects:[NSNumber numberWithInt:functionAppButton.tag],indexPath,[NSNumber numberWithInt:i],nil];
NSArray *catdictKey=[NSArray arrayWithObjects:#"btn",#"indexPath",#"no",nil];
NSDictionary *catPassdict=[NSDictionary dictionaryWithObjects:catdictObject forKeys:catdictKey];
[NSThread detachNewThreadSelector:#selector(displayingSmallImageForFunctionsApps:) toTarget:self withObject:catPassdict];
}
else
{
if(![object isKindOfClass:[NSNull class]]){
UIImage *img = (UIImage *)object;
[functionAppButton setImage:img forState:UIControlStateNormal];
}
-(void)displayingSmallImageForFunctionsApps:(NSDictionary *)dict
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSIndexPath *path=[dict objectForKey:#"indexPath"];
NSArray *catArray=[self.functionDataDictionary objectForKey:[self.functionsKeysArray objectAtIndex:path.row]];
int vlaue=[[dict objectForKey:#"no"] intValue];
NSDictionary *dict1=[catArray objectAtIndex:vlaue];
NSString *urlString=[dict1 objectForKey:#"artwork_url_large"];
NSURL *url = [NSURL URLWithString:urlString];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
if(image){
[imageDictFunctionApp setObject:image forKey:[NSString stringWithFormat:#"%d",[[dict objectForKey:#"btn"] intValue]]];
NSMutableDictionary *dict2=[NSMutableDictionary dictionaryWithCapacity:4];
[dict2 setObject:image forKey:#"imageValue"];
[dict2 setObject:[dict objectForKey:#"btn"] forKey:#"tag"];
[dict2 setObject:[dict objectForKey:#"indexPath"] forKey:#"indexPath"];
[self performSelectorOnMainThread:#selector(setImageInCellDictCategroryTable:) withObject:dict2 waitUntilDone:NO];
}
else{
[imageDictFunctionApp setObject:[NSNull null] forKey:[NSString stringWithFormat:#"%d",[[dict objectForKey:#"btn"] intValue]]];
}
[pool drain];
}
- (void)setImageInCellDictCategroryTable:(NSDictionary *)dict{
UITableViewCell *myCell = (UITableViewCell *)[categoriesAndFunctionsTableView cellForRowAtIndexPath:[dict objectForKey:#"indexPath"]];
UIButton *myBtn = (CustomUIButton *)[myCell viewWithTag:[[dict objectForKey:#"tag"] intValue]];
if ([dict objectForKey:#"imageValue"]) {
[myBtn setImage:[dict objectForKey:#"imageValue"] forState:UIControlStateNormal];
}
}
I have posted all my code that might be linked with this error.Please anyone suggest me how to solve this issue.
Thanks in advance!
I would suggest not to use threads and move you code to GCD, looks like what you want to use is a serial queue.
So what I would guess is happening is that you are running out of Mach ports. It looks to me like you are starting a thread for every single cell in your table and then they are all trying to schedule tasks to run on the main runloop when they are done. This is going to stress your system.
I would create an NSOperation for each image and schedule them all on the same NSOperationQueue. The runtime will use a pool of threads tuned to the specific system to run all of the operations.
For a simple thing like this, you can also use GCD as Oscar says, but I recently read on the Apple list that NSOperationQueue is preferred because it is higher level. It gives you more options for controlling what happens to your background tasks.

UIImagePicker crashing after selection

I'm using ELCImagePickerController so I can select multiple photos and import them. It works fine when I select a few photos, but if I select over around 25, I get a crash. Here's the code that runs after I hit done selecting photos:
-(void)selectedAssets:(NSArray*)_assets {
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
int count=0;
for(ALAsset *asset in _assets) {
NSMutableDictionary *workingDictionary = [[NSMutableDictionary alloc] init];
[workingDictionary setObject:[asset valueForProperty:ALAssetPropertyType] forKey:#"UIImagePickerControllerMediaType"];
UIImage *image=[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
[workingDictionary setObject:image forKey:#"UIImagePickerControllerOriginalImage"];
[workingDictionary setObject:[[asset valueForProperty:ALAssetPropertyURLs] valueForKey:[[[asset valueForProperty:ALAssetPropertyURLs] allKeys] objectAtIndex:0]] forKey:#"UIImagePickerControllerReferenceURL"];
NSLog(#"%i", count);
count++;
[returnArray addObject:workingDictionary];
}
[self popToRootViewControllerAnimated:NO];
[[self parentViewController] dismissModalViewControllerAnimated:YES];
if([delegate respondsToSelector:#selector(elcImagePickerController:didFinishPickingMediaWithInfo:)]) {
[delegate performSelector:#selector(elcImagePickerController:didFinishPickingMediaWithInfo:) withObject:self withObject:[NSArray arrayWithArray:returnArray]];
}
}
I selected 80 photos, and the NSLog statement displays up to 45, but then it just crashes with no message, just (gdb).
The images I'm selecting are iPhone 4 images captured with the rear camera. I've tried resizing the images too upon importing, but even then the app still crashes. Any ideas of what could be the problem?
I'm going to put that as an answer if you don't mind.
There are few solutions to this problem. First you might want to restrict user from selecting more than something like 5 photos. Second you might want to resize your images and make them really small before putting them into an array or something. Or if you need them all in the original size, you can copy them upon selection to your ~/tmp directory and instead store the links to them in your NSArray, so that you could load them dynamically from disk instead of keeping them all in memory.
Sorry if it doesn't helps since I don't really know your ultimate goal in using such amount of images at the same time.

UIWebView loading

I want load the html data in webview. At the button click, it open the viewcontroller and load the html data in this viewcontroller (add web view in this view controller using Interface builder). When the html data not proper loading and i press the back button, at that time crash the app. i am not doing allocation & init webview in the coding. set IBOUTLET using Interface builder & bind it.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *strResponce = [[NSString alloc] initWithData:jsonData_Info encoding:NSUTF8StringEncoding];
[jsonData_Info release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
self.jsonArray_Info=[json objectWithString:strResponce error:&error];
str_InfoDetail = [[self.jsonArray_Info objectAtIndex:0] valueForKey:#"Page"];
str_html = [NSString stringWithFormat:#"%#",str_InfoDetail];
NSString *temp;
temp = [NSString stringWithFormat:#"<html><head><style>body{background-color:transparent;}</style></head><body><span style='color:white'>%#</span></body></html>",str_html];
//web_Information = [[UIWebView alloc]init];
web_Information.backgroundColor=[UIColor clearColor];
web_Information.opaque= NO;
[web_Information loadHTMLString:temp baseURL:nil];
[act stopAnimating];
[strResponce release];
}
please give me any solution.
thanks.
Pls post some code and crash log if you need answers. By the look of it I think it may be because of implementation of UIWebView delegate in your class. I think when you navigate back you do not make the delegate nil which can cause the app to crash

iPhone - tracking back button

I have a tableView which lists the contents of my document directory. I have some zip files in that. If I touch a file in the tableView, the corresponding zip file is unzipped and extracted in a temporary directory(newFilePath in my case). The contents unzipped is listed in the next tableView. When I touch the back button, the contents in the directory is listed again.
For example, consider that I have four zip files in my document directory.
songs.zip, videos.zip, files.zip, calculation.zip
When I run the application, all the four files are listed in the tableView. When I touch songs.zip, this file is extracted in the newFilePath and its contents are pushed to the next tableView. When I touch back, the previous tableView, i.e, the four files in the document directory are listed again. Everything works perfect.
The problem is, the extracted files in the newFilePath remains there itself. They occupy the memory unnecessarily. I want them to be removed from that path when I touch the back button, i.e, I want to make newFilePath empty when the back button is touched.
I tried for it. But, no use. I tried removeItemAtPath: method in viewWillAppear: and also in viewWillDisappear:. But it didnt work in both the cases.
Is there any other method to track the action of the back button? I want an event to take place when the back button is touched. So please help me by sharing your ideas. Here is my code for your verification.
This is my didSelectRowAtIndexPath:
NSString *filePath = //filePath
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSLog(#"File exists at path: %#", filePath);
} else {
NSLog(#"File does not exists at path: %#", filePath);
}
ZipArchive *zip = [[ZipArchive alloc] init];
NSString *newFilePath = //newFilePath
[[NSFileManager defaultManager] createDirectoryAtPath:newFilePath withIntermediateDirectories:NO attributes:nil error:nil];
BOOL result = NO;
if([zip UnzipOpenFile:filePath]) {
//zip file is there
if ([zip UnzipFileTo:newFilePath overWrite:YES]) {
//unzipped successfully
NSLog(#"Archive unzip Success");
result= YES;
} else {
NSLog(#"Failure To Extract Archive, maybe password?");
}
} else {
NSLog(#"Failure To Open Archive");
}
iDataTravellerAppDelegate *AppDelegate = (iDataTravellerAppDelegate *)[[UIApplication sharedApplication] delegate];
//Prepare to tableview.
MyFilesList *myFilesList = [[MyFilesList alloc] initWithNibName:#"MyFilesList" bundle:[NSBundle mainBundle]];
//Increment the Current View
myFilesList.CurrentLevel += 1;
viewPushed = YES;
//Push the new table view on the stack
myFilesList.directoryContent = [AppDelegate getTemporaryDirectoryItemList:newFilePath];
[myFilesList setTitle:detailedViewController.strName];
[self.navigationController pushViewController:myFilesList animated:YES];
[myFilesList release];
Thank you for your answers.
Oh ya, thats quite simple:
in LoadView,
self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]
initWithTitle:#"Back"
style:UIBarButtonItemStylePlain
target:self
action:#selector(backButtonHit)];
-(void)backButtonHit
{
// removeItemAtPath: newFilepath stuff here
[self.navigationController popViewControllerAnimated:YES];
}

release NSMutable array in obj-c

where to dealloc/ release my NS-mutable array a1 ??
see this
- (void)viewDidLoad {
[NSThread detachNewThreadSelector:#selector(loadImage) toTarget:self withObject:nil];
}
- (void) loadImage
{
NSLog(#" THREAD METHOD");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSUserDefaults *imgg = [NSUserDefaults standardUserDefaults];
myimg= [imgg stringForKey:#"keyToimg"];
NSLog(#"RES image sssssssss is = %#",myimg);
a1 = [[NSMutableArray alloc] init];
[a1 addObjectsFromArray:[myimg componentsSeparatedByString:#"\n\t"]];
//[a1 removeAllObjects];
////
//[myimg release];
[pool release];
}
and in table cell of secition 3 i am displaying image
switch(indexPath.section)
{
NSString *urlE=[a1 objectAtIndex:1];
NSLog(#"url is %#",urlE);
NSData *backgroundData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlE]];
image = [UIImage imageWithData:backgroundData];
myImageView= [[UIImageView alloc] initWithImage:image];
[myImageView setUserInteractionEnabled:YES];
CGRect rect=CGRectMake(20 ,10, 270, 180);
myImageView.frame = rect;
myImageView.tag = i;
[cell.contentView addSubview:myImageView];
}
and based on tap images are changing
pragma mark working image tap
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#" life count %d",[myimg retainCount]);
NSLog(#" life array count %d",[a1 retainCount]);
//NSLog(#" GITSHffffffffffffffffffffffffffffffC");
NSUInteger sections = [indexPath section];
//NSLog(#"row is %d",sections);
if (sections == 3)
{ //Its either 1 or 0 I don't remember, it's been a while since I did some tableview
if(tap<[a1 count]-1) {
NSLog(#" life array count %d",[a1 retainCount]);
tap++;
NSString *sa=[a1 objectAtIndex:tap];
//////////////////////
image= [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat: sa,[a1 objectAtIndex:tap ]]]]];
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0)];
myImageView.image = image;
//[myimg release];
//[a1 release];
}
else {
tap=1;
//[myimg release];
//[a1 release];
}
}
//[a1 release];
}
so where should i release my a1 and myimg
a1 will never be released using this code.
You should put it on a member variable or add autorelease after init.
By the way, your myImageView should be released after you add it to the cell view.
It is possible because of the retain/release logic: when you alloc the myImageView the retain count is +1, once you add it to cell view,it is now +2, you should then release it so that the retain comes back to +1 and then when cell view will be further deallocated, it will decrement the retain count to 0.
The same logic for the variable image in the last function
Regards
Meir assayag
Instead of :
a1 = [[NSMutableArray alloc] init];
[a1 addObjectsFromArray:[myimg componentsSeparatedByString:#"\n\t"]];
Consider:
a1 = [NSMutableArray arrayWithArray:[myimg componentsSeparatedByString:#"\n\t"]];
That'll initialize your a1 with an autoreleased NSMutableArray object, and then you don't have to worry about manually releasing it.
The thing I don't know is whether your [pool release] will release it, but... I'd really prefer you NOT put that business in a background thread, but rather use asynchronous network methods to get your image data.
By the way, as I was learning iPhone development, I went through three or four levels of "aha moments" about backgrounded networking. One of them had to do with running selectors on background threads. That lasted about a week until I discovered ASIHttpRequest, which is how I do it now. MUCH simpler way to put network interactions in the background without having to mess with threading or any of that nonsense. See http://allseeing-i.com/ASIHTTPRequest/
If you look at my answers, every time HTTP client networking comes up I recommend ASI. I really don't mean to be a shill for it--it's just made my life so much easier I think everyone needs to know about it.