Search Results

Search found 42 results on 2 pages for 'nsoperationqueue'.

Page 2/2 | < Previous Page | 1 2 

  • Optimized Image Loading in a UIScrollView

    - by Michael Gaylord
    I have a UIScrollView that has a set of images loaded side-by-side inside it. You can see an example of my app here: http://www.42restaurants.com. My problem comes in with memory usage. I want to lazy load the images as they are about to appear on the screen and unload images that aren't on screen. As you can see in the code I work out at a minimum which image I need to load and then assign the loading portion to an NSOperation and place it on an NSOperationQueue. Everything works great apart from a jerky scrolling experience. I don't know if anyone has any ideas as to how I can make this even more optimized, so that the loading time of each image is minimized or so that the scrolling is less jerky. - (void)scrollViewDidScroll:(UIScrollView *)scrollView{ [self manageThumbs]; } - (void) manageThumbs{ int centerIndex = [self centerThumbIndex]; if(lastCenterIndex == centerIndex){ return; } if(centerIndex >= totalThumbs){ return; } NSRange unloadRange; NSRange loadRange; int totalChange = lastCenterIndex - centerIndex; if(totalChange > 0){ //scrolling backwards loadRange.length = fabsf(totalChange); loadRange.location = centerIndex - 5; unloadRange.length = fabsf(totalChange); unloadRange.location = centerIndex + 6; }else if(totalChange < 0){ //scrolling forwards unloadRange.length = fabsf(totalChange); unloadRange.location = centerIndex - 6; loadRange.length = fabsf(totalChange); loadRange.location = centerIndex + 5; } [self unloadImages:unloadRange]; [self loadImages:loadRange]; lastCenterIndex = centerIndex; return; } - (void) unloadImages:(NSRange)range{ UIScrollView *scrollView = (UIScrollView *)[[self.view subviews] objectAtIndex:0]; for(int i = 0; i < range.length && range.location + i < [scrollView.subviews count]; i++){ UIView *subview = [scrollView.subviews objectAtIndex:(range.location + i)]; if(subview != nil && [subview isKindOfClass:[ThumbnailView class]]){ ThumbnailView *thumbView = (ThumbnailView *)subview; if(thumbView.loaded){ UnloadImageOperation *unloadOperation = [[UnloadImageOperation alloc] initWithOperableImage:thumbView]; [queue addOperation:unloadOperation]; [unloadOperation release]; } } } } - (void) loadImages:(NSRange)range{ UIScrollView *scrollView = (UIScrollView *)[[self.view subviews] objectAtIndex:0]; for(int i = 0; i < range.length && range.location + i < [scrollView.subviews count]; i++){ UIView *subview = [scrollView.subviews objectAtIndex:(range.location + i)]; if(subview != nil && [subview isKindOfClass:[ThumbnailView class]]){ ThumbnailView *thumbView = (ThumbnailView *)subview; if(!thumbView.loaded){ LoadImageOperation *loadOperation = [[LoadImageOperation alloc] initWithOperableImage:thumbView]; [queue addOperation:loadOperation]; [loadOperation release]; } } } } EDIT: Thanks for the really great responses. Here is my NSOperation code and ThumbnailView code. I tried a couple of things over the weekend but I only managed to improve performance by suspending the operation queue during scrolling and resuming it when scrolling is finished. Here are my code snippets: //In the init method queue = [[NSOperationQueue alloc] init]; [queue setMaxConcurrentOperationCount:4]; //In the thumbnail view the loadImage and unloadImage methods - (void) loadImage{ if(!loaded){ NSString *filename = [NSString stringWithFormat:@"%03d-cover-front", recipe.identifier, recipe.identifier]; NSString *directory = [NSString stringWithFormat:@"RestaurantContent/%03d", recipe.identifier]; NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"png" inDirectory:directory]; UIImage *image = [UIImage imageWithContentsOfFile:path]; imageView = [[ImageView alloc] initWithImage:image andFrame:CGRectMake(0.0f, 0.0f, 176.0f, 262.0f)]; [self addSubview:imageView]; [self sendSubviewToBack:imageView]; [imageView release]; loaded = YES; } } - (void) unloadImage{ if(loaded){ [imageView removeFromSuperview]; imageView = nil; loaded = NO; } } Then my load and unload operations: - (id) initWithOperableImage:(id<OperableImage>) anOperableImage{ self = [super init]; if (self != nil) { self.image = anOperableImage; } return self; } //This is the main method in the load image operation - (void)main { [image loadImage]; } //This is the main method in the unload image operation - (void)main { [image unloadImage]; }

    Read the article

  • NSOutlineView not refreshing when objects added to managed object context from NSOperations

    - by John Gallagher
    Background Cocoa app using core data Two processes - daemon and a main UI Daemon constantly writing to a data store UI process reads from same data store NSOutlineView in UI is bound to an NSTreeController which is bound to Application with key path of delegate.interpretedMOC What I want When the UI is activated, the outline view should update with the latest data inserted by the daemon. The Problem Main Thread Approach I fetch all the entities I'm interested in, then iterate over them, doing refreshObject:mergeChanges:YES. This works OK - the items get refreshed correctly. However, this is all running on the main thread, so the UI locks up for 10-20 seconds whilst it refreshes. Fine, so let's move these refreshes to NSOperations that run in the background instead. NSOperation Multithreaded Approach As soon as I move the refreshObject:mergeChanges: call into an NSOperation, the refresh no longer works. When I add logging messages, it's clear that the new objects are loaded in by the NSOperation subclass and refreshed. Not only that, but they are What I've tried I've messed around with this for 2 days solid and tried everything I can think of. Passing objectIDs to the NSOperation to refresh instead of an entity name. Resetting the interpretedMOC at various points - after the data refresh and before the outline view reload. I'd subclassed NSOutlineView. I discarded my subclass and set the view back to being an instance of NSOutlineView, just in case there was any funny goings on here. Added a rearrangeObjects call to the NSTreeController before reloading the NSOutlineView data. Made sure I had set the staleness interval to 0 on all managed object contexts I was using. I've got a feeling this problem is somehow related to caching core data objects in memory. But I've totally exhausted all my ideas on how I get this to work. I'd be eternally grateful of any ideas anyone else has. Code Main Thread Approach // In App Delegate -(void)applicationDidBecomeActive:(NSNotification *)notification { // Delay to allow time for the daemon to save [self performSelector:@selector(refreshTrainingEntriesAndGroups) withObject:nil afterDelay:3]; } -(void)refreshTrainingEntriesAndGroups { NSSet *allTrainingGroups = [[[NSApp delegate] interpretedMOC] fetchAllObjectsForEntityName:kTrainingGroup]; for(JGTrainingGroup *thisTrainingGroup in allTrainingGroups) [interpretedMOC refreshObject:thisTrainingGroup mergeChanges:YES]; NSError *saveError = nil; [interpretedMOC save:&saveError]; [windowController performSelectorOnMainThread:@selector(refreshTrainingView) withObject:nil waitUntilDone:YES]; } // In window controller class -(void)refreshTrainingView { [trainingViewTreeController rearrangeObjects]; // Didn't really expect this to have any effect. And it didn't. [trainingView reloadData]; } NSOperation Multithreaded Approach // In App Delegate -(void)refreshTrainingEntriesAndGroups { JGRefreshEntityOperation *trainingGroupRefresh = [[JGRefreshEntityOperation alloc] initWithEntityName:kTrainingGroup]; NSOperationQueue *refreshQueue = [[NSOperationQueue alloc] init]; [refreshQueue setMaxConcurrentOperationCount:1]; [refreshQueue addOperation:trainingGroupRefresh]; while ([[refreshQueue operations] count] > 0) { [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]]; [windowController performSelectorOnMainThread:@selector(refreshTrainingView) withObject:nil waitUntilDone:YES]; } // JGRefreshEntityOperation.m @implementation JGRefreshEntityOperation @synthesize started; @synthesize executing; @synthesize paused; @synthesize finished; -(void)main { [self startOperation]; NSSet *allEntities = [imoc fetchAllObjectsForEntityName:entityName]; for(id thisEntity in allEntities) [imoc refreshObject:thisEntity mergeChanges:YES]; [self finishOperation]; } -(void)startOperation { [self willChangeValueForKey:@"isExecuting"]; [self willChangeValueForKey:@"isStarted"]; [self setStarted:YES]; [self setExecuting:YES]; [self didChangeValueForKey:@"isExecuting"]; [self didChangeValueForKey:@"isStarted"]; imoc = [[NSManagedObjectContext alloc] init]; [imoc setStalenessInterval:0]; [imoc setUndoManager:nil]; [imoc setPersistentStoreCoordinator:[[NSApp delegate] interpretedPSC]]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:imoc]; } -(void)finishOperation { saveError = nil; [imoc save:&saveError]; if (saveError) { NSLog(@"Error saving. %@", saveError); } imoc = nil; [self willChangeValueForKey:@"isExecuting"]; [self willChangeValueForKey:@"isFinished"]; [self setExecuting:NO]; [self setFinished:YES]; [self didChangeValueForKey:@"isExecuting"]; [self didChangeValueForKey:@"isFinished"]; } -(void)mergeChanges:(NSNotification *)notification { NSManagedObjectContext *mainContext = [[NSApp delegate] interpretedMOC]; [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES]; } -(id)initWithEntityName:(NSString *)entityName_ { [super init]; [self setStarted:false]; [self setExecuting:false]; [self setPaused:false]; [self setFinished:false]; [NSThread setThreadPriority:0.0]; entityName = entityName_; return self; } @end // JGRefreshEntityOperation.h @interface JGRefreshEntityOperation : NSOperation { NSString *entityName; NSManagedObjectContext *imoc; NSError *saveError; BOOL started; BOOL executing; BOOL paused; BOOL finished; } @property(readwrite, getter=isStarted) BOOL started; @property(readwrite, getter=isPaused) BOOL paused; @property(readwrite, getter=isExecuting) BOOL executing; @property(readwrite, getter=isFinished) BOOL finished; -(void)startOperation; -(void)finishOperation; -(id)initWithEntityName:(NSString *)entityName_; -(void)mergeChanges:(NSNotification *)notification; @end

    Read the article

  • Fade animation UITableViewCell

    - by Tomas
    Hi everyone, I have a UITableViewController that populates a UITableView with some data that I pull off the net. The data for each cell consists also of an image used as background, which I'm downloading in a separated NSOperation added to a NSOperationQueue with a MaxConcurrentOperationCount set to 4. As long as the image is not downloaded I'm showing a generic placeholder which I would like to replace (fading out/fading in) with the downloaded image once it's being successfully downloaded. I'm using the following code placed inside the cellForRowAtIndexPath of the UITableViewController. [UIView beginAnimations:@"fade" context:nil]; [UIView setAnimationBeginsFromCurrentState:YES]; [UIView setAnimationDuration:3.0]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; cell.placeholderUIImage.alpha = 0.0; cell.backgroundUIImage.alpha = 1.0; [UIView commitAnimations]; This is unfortunately just working randomly for a couple of rows, since for the most the background image is set instantly, as if the animation started on one cell would have been "overwritten" by the next call of beginAnimations.

    Read the article

  • Putting data from SONObjectWithData to UITableView

    - by user2966615
    i am building a app in which i am getting data from a php file and already NSLoging it in xcode and it is showing data in this format: jsonObject=( ( 1, abc, "[email protected]", "501 B3 Town" ), ( 2, sam, "[email protected]", "502 B3 Town" ), ( 3, jhon, "[email protected]", "503 B Town" ) ) and here is my viewdidload - (void)viewDidLoad { [super viewDidLoad]; statuses=[[NSMutableArray alloc]init]; NSURL *myURL = [NSURL URLWithString:@"http://url/result.php"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSLog(@"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]); id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"jsonObject=%@",jsonObject); statuses = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; }]; } now i want to display all records in uitableview. can anyone tell me how can i do that. Thanks

    Read the article

  • iOS Downloading Videos and saving in Application Support folder

    - by Satyam svv
    In my application, i've to download videos around 10 to my application and play accordingly. Each video is around 50 MB. I'm using following code and then after downloading the video, i'm saving it to Application support folder to avoid icloud sync. But the problem is that when downloading the videos its crashing. [NSURLConnection sendAsynchronousRequest:req queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *rcvdDat, NSError * err) { . . . } What I'm thinking is that, while downloading the video, it resides in memory and so the total memory occupying by the app is increasing. Finally iOS is making the app to close. I would like to download the video and when ever a stream of data received, write to temp file and when completes move it to application support folder. Can some one help me on how to write it to file and save it at the end? I cannot use 3rd party libraries (unless its small) due to legal issues.

    Read the article

  • iPhone - return from an NSOperation

    - by lostInTransit
    Hi I am using a subclass of NSOperation to do some background processes. I want the operation to be cancelled when the user clicks a button. Here's what my NSOperation subclass looks like - (id)init{ self = [super init]; if(self){ //initialization code goes here _isFinished = NO; _isExecuting = NO; } return self; } - (void)start { if (![NSThread isMainThread]) { [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO]; return; } [self willChangeValueForKey:@"isExecuting"]; _isExecuting = YES; [self didChangeValueForKey:@"isExecuting"]; //operation goes here } - (void)finish{ //releasing objects here [self willChangeValueForKey:@"isExecuting"]; [self willChangeValueForKey:@"isFinished"]; _isExecuting = NO; _isFinished = YES; [self didChangeValueForKey:@"isExecuting"]; [self didChangeValueForKey:@"isFinished"]; } - (void)cancel{ [self willChangeValueForKey:@"isCancelled"]; [self didChangeValueForKey:@"isCancelled"]; [self finish]; } And this is how I am adding objects of this class to a queue and listening for KVO notifications operationQueue = [[NSOperationQueue alloc] init]; [operationQueue setMaxConcurrentOperationCount:5]; [operationQueue addObserver:self forKeyPath:@"operations" options:0 context:&OperationsChangedContext]; - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (context == &OperationsChangedContext) { NSLog(@"Queue size: %u", [[operationQueue operations] count]); } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } To cancel an operation (on a button click for instance), I tried calling -cancel but it doesn't make a difference. Also tried calling -finish but even that doesn't change anything. Every time I add an operation to the queue, the queue size only increases. finish is called (checked using NSLog statements) but it doesn't really end the operation. I'm still not very confident I'm doing this right Can someone please tell me where I am going wrong? Thanks a lot

    Read the article

  • Is This a Valid Way to Use Blocks in Objective-C?

    - by Carter
    I've been building a HTTP client that uses web services to synchronize information between the client and server. I've been using Blocks and NSURLConnection to achieve this on the client side, but I'm getting frequent EXC_BAD_ACCESS crashes in objc_msgSend(). From what I understand, this usually means that a stored block that has fallen off the stack has been called. I think I've coded things correctly to avoid this, but I'm still stuck. Here is conceptually what my code is doing. It starts by calling "synchronizeWithWebServer". That method invokes "listRootObjectsOnServerWithBlock:" which takes in a block to be called when the method returns. "listRootObjectsOnServersWithBlock:" initiates a NSURLConnection to the web server asynchronously. It to expects a block to be called when it returns. Inside that block I want to be able to execute the original Block (so aptly named 'block'). This is only a simplified version of my code. The real synchronization process is more complex but it's mostly more of the same as what you see below. Sometimes the code works perfectly, but about 80% of the time it crashes very early on in the routine. It seems to be more vulnerable to crashing when my data set gets larger. - (void)synchronizeWithWebServer { [self listRootObjectsOnServerWithBlock:^(NSArray *results, NSError *error) { //Iterate over result objects and perform some other similar routines. }]; } - (void)listRootObjectsOnServerWithBlock:(void (^)(NSArray *results, NSError *error))block { //Create NSURLRequest Here //Create connection asynchronously. block = [block copy]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){ //Parse response from web server (stored in NSData *data) NSArray *results = ..... //Call 'block' block(results, error); [block release]; }]; }

    Read the article

  • Cocoa UI Elements Not Updating

    - by spamguy
    I have a few Cocoa UI elements with outlet connexions to an object instantiated within an NSView object, which is in turn put there by an NSViewController. These elements, a definite progress bar and a text label, are not updating: the progress bar is dead and empty despite having its value change constantly, the text label does not unhide through [textLabel setHidden:NO], the text label does not change its string. What I know: There's no difference between binding values and setting them in code. Nothing changes either way. I've checked outlet connections. They're all there. I've tried [X displayIfNeeded], where X has been the UI objects themselves, the containing NSView, and the main window. No difference. [progressBar setUsesThreadedAnimation:YES] makes no difference. Interestingly, if I look at progressBar mid-program, _threadedAnimation is still NO. The object holding all these outlets and performing an import operation is in an NSOperationQueue owned by the NSViewController object. Thanks! EDIT: As suggested, I called [self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithInt:myObject] waitUntilDone:NO]. (I've also tried waitUntilDone:YES.) It's still not updating. The debugger clearly shows updateProgress: taking place in the main thread, so I don't know what's missing.

    Read the article

  • In app purchase on iphone.: How to receive your available products *before* someone may be able to b

    - by Thorsten S.
    Currently I am loading my supported products from a plist and after that I send a SKProductsRequest to guarantee that my SKProducts are still valid. So I set up the request, start it and get the response in: (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response Now, so far all functions correctly. Problem: From calling the request until receiving the response it may last several seconds. Until that my app is already loaded and the user may be able to choose and buy a product. But because no products have been received, the available products are not in sync with the validated products - unlikely, but possible error. So my idea is to wait until the data is loaded and only continue when the list is validated. (Just a few seconds waiting...). I have a singleton instance managing all products. + (MyClass *) sharedInstance { if (!sharedInstance) sharedInstance = [MyClass new]; // Now wait until we have our data [condition lock]; while (noEntriesYet) // is yes at begin [condition wait]; [condition unlock]; return sharedInstance; } - productsRequest: didReceiveResponse: { [condition lock]; // I have my data noEntriesYet = false; [condition signal]; [condition unlock]; } Problem: The app freezes. Everything works fine if didReceiveResponse is completed before the sharedInstance is queried. There are different threads, the lock is working if wait is reached during didReceiveResponse, everything fine. But if not, didReceiveResponse is never called even if the request was sent. The lock is released, everything looks ok. I have tried to send the product request in a separate NSThread, with NSOperationQueue...without avail. Why ? What is happening ? How to solve the problem ?

    Read the article

  • UIDocumentInteractionController & ARC: [UIPopoverController dealloc] reached while popover is still visible

    - by muffel
    This issue or similar issues have been discussed here before, but I didn't find any working solution for me. I am using the following code to display a UIDocumentInteractionController on an ARC-enabled iOS 7 project: - (void) exportDoc{ // [...] docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path]]; docController.delegate = self; [docController presentOpenInMenuFromBarButtonItem:mainMenuButton animated:YES]; } First I didn't want to create a property that holds the controller reference, but as many people said that there are not alternatives to it. It is defined as @property (strong) UIDocumentInteractionController* docController; exportDoc is run in the main thread using NSOperationQueue. Whenever it is executed, I get the following error message: Terminating app due to uncaught exception 'NSGenericException', reason: '-[UIPopoverController dealloc] reached while popover is still visible.' This is what the backtrace says: (lldb) bt * thread #1: tid = 0x1c97d9, 0x000000019a23c1c0 libobjc.A.dylibobjc_exception_throw, queue = 'com.apple.main-thread', stop reason = breakpoint 2.1 frame #0: 0x000000019a23c1c0 libobjc.A.dylibobjc_exception_throw frame #1: 0x000000018d982e90 CoreFoundation+[NSException raise:format:] + 128 frame #2: 0x0000000190bc348c UIKit-[UIPopoverController dealloc] + 96 frame #3: 0x0000000190e18fc8 UIKit-[UIDocumentInteractionController dealloc] + 168 frame #4: 0x000000019a255474 libobjc.A.dylib(anonymous namespace)::AutoreleasePoolPage::pop(void*) + 524 frame #5: 0x000000018d881988 CoreFoundation_CFAutoreleasePoolPop + 28 frame #6: 0x000000018e42cb18 Foundation-[NSOperationInternal _start:] + 892 frame #7: 0x000000018e4eea38 Foundation__NSOQSchedule_f + 76 frame #8: 0x000000019a813fd4 libdispatch.dylib_dispatch_client_callout + 16 frame #9: 0x000000019a8171dc libdispatch.dylib_dispatch_main_queue_callback_4CF + 336 frame #10: 0x000000018d942c2c CoreFoundation__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 12 frame #11: 0x000000018d940f6c CoreFoundation__CFRunLoopRun + 1452 frame #12: 0x000000018d881c20 CoreFoundationCFRunLoopRunSpecific + 452 frame #13: 0x0000000193511c0c GraphicsServicesGSEventRunModal + 168 frame #14: 0x00000001909b2fdc UIKitUIApplicationMain + 1156 * frame #15: 0x000000010000947c MyApplicationmain(argc=1, argv=0x000000016fdfbc80) + 108 at main.m:16 frame #16: 0x000000019a82faa0 libdyld.dylibstart + 4 As far as I understand the autoreleasepool just releases the controller. Shouldn't this be prevented by using a strong property just as I did? Do you have any idea what the problem can be and how I can solve it?

    Read the article

  • Clarification on Threads and Run Loops In Cocoa

    - by dubbeat
    I'm trying to learn about threading and I'm thoroughly confused. I'm sure all the answers are there in the apple docs but I just found it really hard to breakdown and digest. Maybe somebody could clear a thing or 2 up for me. 1)performSelectorOnMainThread Does the above simply register an event in the main run loop or is it somehow a new thread even though the method says "mainThread"? If the purpose of threads is to relieve processing on the main thread how does this help? 2) RunLoops Is it true that if I want to create a completely seperate thread I use "detachNewThreadSelector"? Does calling start on this initiate a default run loop for the thread that has been created? If so where do run loops come into it? 3) And Finally , I've seen examples using NSOperationQueue. Is it true to say that If you use performSelectorOnMainThread the threads are in a queue anyway so NSOperation is not needed? 4) Should I forget about all of this and just use the Grand Central Dispatch instead?

    Read the article

  • iPhone: Speeding up a search that's polling 17,000 Core Data objects

    - by randombits
    I have a class that conforms to UISearchDisplayDelegate and contains a UISearchBar. This view is responsible for allowing the user to poll a store of about 17,000 objects that are currently managed by Core Data. Everytime the user types in a character, I created an instance of a SearchOperation (subclasses NSOperation) that queries Core Data to find results that might match the search. The code in the search controller looks something like: - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { // Update the filtered array based on the search text and scope in a secondary thread if ([searchText length] < 3) { [filteredList removeAllObjects]; // First clear the filtered array. [self setFilteredList:NULL]; [self.tableView reloadData]; return; } NSDictionary *searchdict = [NSDictionary dictionaryWithObjectsAndKeys:scope, @"scope", searchText, @"searchText", nil]; [aSearchQueue cancelAllOperations]; SearchOperation *searchOp = [[SearchOperation alloc] initWithDelegate:self dataDict:searchdict]; [aSearchQueue addOperation:searchOp]; } And my search is rather straight forward. SearchOperation is a subclass of NSOperation. I overwrote the main method with the following code: - (void)main { if ([self isCancelled]) { return; } NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:managedObjectContext]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity:entity]; NSPredicate *predicate = NULL; predicate = [NSPredicate predicateWithFormat:@"(someattr contains[cd] %@)", searchText]; [fetchRequest setPredicate:predicate]; NSError *error = NULL; NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; [fetchRequest release]; if (self.delegate != nil) [self.delegate didFinishSearching:fetchResults]; [pool drain]; } This code works, but it has several issues. It's slow. Even though I have the search happening in a separate thread other than the UI thread, querying 17,000 objects is clearly not optimal. If I'm not careful, crashes can happen. I set the max concurrent searches in my NSOperationQueue to 1 to avoid this. What else can I do to make this search faster? I think preloading all 17,000 objects into memory might be risky. There has to be a smarter way to conduct this search to give results back to the user faster.

    Read the article

  • Running out of memory with UIImage creation on an offscreen Bitmap Context by NSOperation

    - by sigsegv
    I have an app with multiple UIView subclasses that acts as pages for a UIScrollView. UIViews are moved back and forth to provide a seamless experience to the user. Since the content of the views is rather slow to draw, it's rendered on a single shared CGBitmapContext guarded by locks by NSOperation subclasses - executed one at once in an NSOperationQueue - wrapped up in an UIImage and then used by the main thread to update the content of the views. -(void)main { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc]init]; if([self isCancelled]) { return; } if(nil == data) { return; } // Buffer is the shared instance of a CG Bitmap Context wrapper class // data is a dictionary CGImageRef img = [buffer imageCreateWithData:data]; UIImage * image = [[UIImage alloc]initWithCGImage:img]; CGImageRelease(img); if([self isCancelled]) { [image release]; return; } NSDictionary * result = [[NSDictionary alloc]initWithObjectsAndKeys:image,@"image",id,@"id",nil]; // target is the instance of the UIView subclass that will use // the image [target performSelectorOnMainThread:@selector(updateContentWithData:) withObject:result waitUntilDone:NO]; [result release]; [image release]; [pool release]; } The updateContentWithData: of the UIView subclass performed on the main thread is just as simple -(void)updateContentWithData:(NSDictionary *)someData { NSDictionary * data = [someData retain]; if([[data valueForKey:@"id"]isEqualToString:[self pendingRequestId]]) { UIImage * image = [data valueForKey:@"image"]; [self setCurrentImage:image]; [self setNeedsDisplay]; } // If the image has not been retained, it should be released together // with the dictionary retaining it [data release]; } The drawLayer:inContext: method of the subclass will just get the CGImage from the UIImage and use it to update the backing layer or part of it. No retain or release is involved in the process. The problem is that after a while I run out of memory. The number of the UIViews is static. CGImageRef and UIImage are created, retained and released correctly (or so it seems to me). Instruments does not show any leaks, just the free memory available dip constantly, rise a few times, and then dip even lower until the application is terminated. The app cycles through about 2-300 of the aforementioned pages before that, but I would expect to have the memory usage reach a more or less stable level of used memory after a bunch of pages have been already skimmed at fast speed or, since the images are up to 3MB in size, deplete way earlier. Any suggestion will be greatly appreciated.

    Read the article

  • Memory Management iOS dev app doesn't work after a few detail items

    - by user1434846
    I am working on a project with a tableView controller and the detail views contains CMMotionManager.When i open 5 or 6 detailViews all goes well,but after a while the app goes slow and finally crashes.On instruments the only leak is on main.m , also i must say that I'm using ARC and i can't dealloc or realese the instances. Here is the code: First the table view: - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.title = @"Movement";//Master View Controller title bar UIImage *image = [UIImage imageNamed:@"jg_navibar.png"]; [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; //Init the array with data bodypartsMutableArray = [NSMutableArray arrayWithCapacity:26]; BodypartData *part1 = [[BodypartData alloc] init]; part1.bodypartname = @"Shoulder"; part1.movementname = @"Flexion"; part1.fullimageStartingPosition=[UIImage imageNamed:@"2_shoulder_flexion_end_position.jpg"]; part1.fullimageEndedPosition=[UIImage imageNamed:@"2_shoulder_flexion_end_position.jpg"]; part1.thumbimage=[UIImage imageNamed:@"1_shoulder_flexion_landmarks_thumb.jpg"]; [bodypartsMutableArray addObject:part1]; ......... } then the cell: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyBasicCell"]; BodypartData *part = [self.bodypartsMutableArray objectAtIndex:indexPath.row]; cell.textLabel.text =[NSString stringWithFormat:part.movementname]; cell.detailTextLabel.text =[NSString stringWithFormat:part.bodypartname]; cell.imageView.image =part.thumbimage; return cell; } and the the detailViewdid load: - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // Init motionManager object and set the Update Interval _motionManager = [[CMMotionManager alloc]init]; _motionManager.deviceMotionUpdateInterval=1/60; //60 Hz [_motionManager startGyroUpdates]; if (_motionManager.gyroAvailable) { _motionManager.gyroUpdateInterval = 1.0/60.0; [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler: ^(CMDeviceMotion *motion, NSError *error) { CMAttitude *attitude = motion.attitude; //Calculation with rotationMatrix m11 = [NSString stringWithFormat:@"%.02f", attitude.rotationMatrix.m11]; m12 = [NSString stringWithFormat:@"%.02f", attitude.rotationMatrix.m12]; m13 = [NSString stringWithFormat:@"%.02f", attitude.rotationMatrix.m13]; ......... }

    Read the article

  • NSURLConnection request seems to disappear into thin air

    - by ibergmark
    Hi Everybody! I'm having trouble with a NSURLConnection request. My app calls a routine called sayHello to identify a user's device. This code works fine for all devices I've tested it on, but for some devices the request just seems to disappear into thin air with no errors or popups on the device. One specific device that fails is an iPod Touch 2G running OS 3.1.3. The app start's fine and doesn't crash, and none of my error popup messages are displayed. I just can't understand why my server never receives the request since the call to initWithRequest returns a pointer. Any help is much appreciated. Thanks. Here's the relevant header info: @interface Globals : NSObject { UserItem *userData; NSURLConnection *urlConnection; NSString *imageCacheLocation; NSOperationQueue *opQueue; } Here's the implementation of sayHello: - (void)sayHello:(BOOL)updateVisits; { NSString *updString; if (updateVisits) updString = @"Y"; else updString = @"N"; NSDictionary *dataDict = [[NSDictionary alloc] initWithObjectsAndKeys: [[UIDevice currentDevice] uniqueIdentifier], @"id", kProgVersion, @"pv", @"1", @"pr", userData.tagID, @"tg", updString, @"uv", nil]; NSString *urlString = [[NSString alloc] initWithString:kHelloURL]; urlConnection = [self localPOST:dataDict toUrl:urlString delegate:self]; [dataDict release]; [urlString release]; } - (NSURLConnection *)localPOST:(NSDictionary *)dictionary toUrl:(NSString *)urlString delegate:(id)delegate { NSString *myBounds = [[NSString alloc] initWithString:@"0xKmYbOuNdArY"]; NSMutableData *myPostData = [[NSMutableData alloc] initWithCapacity:10]; NSArray *formKeys = [dictionary allKeys]; for (int i = 0; i < [formKeys count]; i++) { [myPostData appendData:[[NSString stringWithFormat:@"--%@\n", myBounds] dataUsingEncoding:NSUTF8StringEncoding]]; [myPostData appendData:[[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"%@\"\n\n%@\n", [formKeys objectAtIndex:i], [dictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSUTF8StringEncoding]]; } [myPostData appendData:[[NSString stringWithFormat:@"--%@--\n", myBounds] dataUsingEncoding:NSUTF8StringEncoding]]; NSURL *myURL = [[NSURL alloc] initWithString:urlString]; NSMutableURLRequest *myRequest = [[NSMutableURLRequest alloc] initWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30]; NSString *myContent = [[NSString alloc] initWithFormat: @"multipart/form-data; boundary=%@", myBounds]; [myRequest setValue:myContent forHTTPHeaderField:@"Content-Type"]; [myRequest setHTTPMethod:@"POST"]; [myRequest setHTTPBody:myPostData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:delegate]; if (!connection) { [[Globals sharedGlobals] showAlertWithTitle: NSLocalizedString( @"Connection failed", @"alert title - connection failed") message: NSLocalizedString( @"Could not open a connection.", @"alert message - connection failed")]; } [myBounds release]; [myPostData release]; [myURL release]; [myRequest release]; [myContent release]; return connection; } - (void)handleNetworkError:(NSError *)error { if (networkErrorAlert) return; networkErrorAlert = YES; [[Globals sharedGlobals] showAlertWithTitle: NSLocalizedString( @"Network error", @"alert title - network error") message: [NSString stringWithFormat: NSLocalizedString( @"This app needs a network connection to function properly.", @"alert message - network error")] otherButtons:nil delegate:self]; } - (void) connectionDidFinishLoading:(NSURLConnection *)connection { [urlConnection release]; urlConnection = nil; } - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self handleNetworkError:error]; [urlConnection release]; urlConnection = nil; }

    Read the article

  • Reducing lag when downloading large amount of data from webpage

    - by Mahir
    I am getting data via RSS feeds and displaying each article in a table view cell. Each cell has an image view, set to a default image. If the page has an image, the image is to be replaced with the image from the article. As of now, each cell downloads the source code from the web page, causing the app to lag when I push the view controller and when I try scrolling. Here is what I have in the cellForRowAtIndexPath: method. NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: @"link"]; storyLink = [storyLink stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSString *sourceCode = [NSString stringWithContentsOfURL:[NSURL URLWithString:storyLink] encoding:NSUTF8StringEncoding error:&error]; NSString *startPt = @"instant-gallery"; NSString *startPt2 = @"<img src=\""; if ([sourceCode rangeOfString:startPt].length != 0) { //webpage has images // find the first "<img src=...>" tag starting from "instant-gallery" NSString *trimmedSource = [sourceCode substringFromIndex:NSMaxRange([sourceCode rangeOfString:startPt])]; trimmedSource = [trimmedSource substringFromIndex:NSMaxRange([trimmedSource rangeOfString:startPt2])]; trimmedSource = [trimmedSource substringToIndex:[trimmedSource rangeOfString:@"\""].location]; NSURL *url = [NSURL URLWithString:trimmedSource]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [UIImage imageWithData:data]; cell.picture.image = image; Someone suggested using NSOperationQueue. Would this way be a good solution? EDIT: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"FeedCell"; LMU_LAL_FeedCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"LMU_LAL_FeedCell" owner:self options:nil]; cell = (LMU_LAL_FeedCell*) [nib objectAtIndex:0]; } int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1]; NSString *untrimmedTitle = [[stories objectAtIndex: storyIndex] objectForKey: @"title"]; cell.title.text = [untrimmedTitle stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; CGSize maximumLabelSize = CGSizeMake(205,9999); CGSize expectedLabelSize = [cell.title.text sizeWithFont:cell.title.font constrainedToSize:maximumLabelSize]; //adjust the label to the the new height. CGRect newFrame = cell.title.frame; newFrame.size.height = expectedLabelSize.height; cell.title.frame = newFrame; //position frame of date label CGRect dateNewFrame = cell.date.frame; dateNewFrame.origin.y = cell.title.frame.origin.y + cell.title.frame.size.height + 1; cell.date.frame = dateNewFrame; cell.date.text = [self formatDateAtIndex:storyIndex]; dispatch_queue_t someQueue = dispatch_queue_create("cell background queue", NULL); dispatch_async(someQueue, ^(void){ NSError *error = nil; NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: @"link"]; storyLink = [storyLink stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSString *sourceCode = [NSString stringWithContentsOfURL:[NSURL URLWithString:storyLink] encoding:NSUTF8StringEncoding error:&error]; NSString *startPt = @"instant-gallery"; NSString *startPt2 = @"<img src=\""; if ([sourceCode rangeOfString:startPt].length != 0) { //webpage has images // find the first "<img src=...>" tag starting from "instant-gallery" NSString *trimmedSource = [sourceCode substringFromIndex:NSMaxRange([sourceCode rangeOfString:startPt])]; trimmedSource = [trimmedSource substringFromIndex:NSMaxRange([trimmedSource rangeOfString:startPt2])]; trimmedSource = [trimmedSource substringToIndex:[trimmedSource rangeOfString:@"\""].location]; NSURL *url = [NSURL URLWithString:trimmedSource]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [UIImage imageWithData:data]; dispatch_async(dispatch_get_main_queue(), ^(void){ cell.picture.image = image; }); }) //error: expected expression } return cell; //error: expected identifier } //error extraneous closing brace

    Read the article

  • how do you make a "concurrent queue safe" lazy loader (singleton manager) in objective-c

    - by Rich
    Hi, I made this class that turns any object into a singleton, but I know that it's not "concurrent queue safe." Could someone please explain to me how to do this, or better yet, show me the code. To be clear I want to know how to use this with operation queues and dispatch queues (NSOperationQueue and Grand Central Dispatch) on iOS. Thanks in advance, Rich EDIT: I had an idea for how to do it. If someone could confirm it for me I'll do it and post the code. The idea is that proxies make queues all on their own. So if I make a mutable proxy (like Apple does in key-value coding/observing) for any object that it's supposed to return, and always return the same proxy for the same object/identifier pair (using the same kind of lazy loading technique as I used to create the singletons), the proxies would automatically queue up the any messages to the singletons, and make it totally thread safe. IMHO this seems like a lot of work to do, so I don't want to do it if it's not gonna work, or if it's gonna slow my apps down to a crawl. Here's my non-thread safe code: RMSingletonCollector.h // // RMSingletonCollector.h // RMSingletonCollector // // Created by Rich Meade-Miller on 2/11/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import <Foundation/Foundation.h> #import "RMWeakObjectRef.h" struct RMInitializerData { // The method may take one argument. // required SEL designatedInitializer; // data to pass to the initializer or nil. id data; }; typedef struct RMInitializerData RMInitializerData; RMInitializerData RMInitializerDataMake(SEL initializer, id data); @interface NSObject (SingletonCollector) // Returns the selector and data to pass to it (if the selector takes an argument) for use when initializing the singleton. // If you override this DO NOT call super. + (RMInitializerData)designatedInitializerForIdentifier:(NSString *)identifier; @end @interface RMSingletonCollector : NSObject { } + (id)collectionObjectForType:(NSString *)className identifier:(NSString *)identifier; + (id<RMWeakObjectReference>)referenceForObjectOfType:(NSString *)className identifier:(NSString *)identifier; + (void)destroyCollection; + (void)destroyCollectionObjectForType:(NSString *)className identifier:(NSString *)identifier; @end // ==--==--==--==--==Notifications==--==--==--==--== extern NSString *const willDestroySingletonCollection; extern NSString *const willDestroySingletonCollectionObject; RMSingletonCollector.m // // RMSingletonCollector.m // RMSingletonCollector // // Created by Rich Meade-Miller on 2/11/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import "RMSingletonCollector.h" #import <objc/objc-runtime.h> NSString *const willDestroySingletonCollection = @"willDestroySingletonCollection"; NSString *const willDestroySingletonCollectionObject = @"willDestroySingletonCollectionObject"; RMInitializerData RMInitializerDataMake(SEL initializer, id data) { RMInitializerData newData; newData.designatedInitializer = initializer; newData.data = data; return newData; } @implementation NSObject (SingletonCollector) + (RMInitializerData)designatedInitializerForIdentifier:(NSString *)identifier { return RMInitializerDataMake(@selector(init), nil); } @end @interface RMSingletonCollector () + (NSMutableDictionary *)singletonCollection; + (void)setSingletonCollection:(NSMutableDictionary *)newSingletonCollection; @end @implementation RMSingletonCollector static NSMutableDictionary *singletonCollection = nil; + (NSMutableDictionary *)singletonCollection { if (singletonCollection != nil) { return singletonCollection; } NSMutableDictionary *collection = [[NSMutableDictionary alloc] initWithCapacity:1]; [self setSingletonCollection:collection]; [collection release]; return singletonCollection; } + (void)setSingletonCollection:(NSMutableDictionary *)newSingletonCollection { if (newSingletonCollection != singletonCollection) { [singletonCollection release]; singletonCollection = [newSingletonCollection retain]; } } + (id)collectionObjectForType:(NSString *)className identifier:(NSString *)identifier { id obj; NSString *key; if (identifier) { key = [className stringByAppendingFormat:@".%@", identifier]; } else { key = className; } if (obj = [[self singletonCollection] objectForKey:key]) { return obj; } // dynamic creation. // get a class for Class classForName = NSClassFromString(className); if (classForName) { obj = objc_msgSend(classForName, @selector(alloc)); // if the initializer takes an argument... RMInitializerData initializerData = [classForName designatedInitializerForIdentifier:identifier]; if (initializerData.data) { // pass it. obj = objc_msgSend(obj, initializerData.designatedInitializer, initializerData.data); } else { obj = objc_msgSend(obj, initializerData.designatedInitializer); } [singletonCollection setObject:obj forKey:key]; [obj release]; } else { // raise an exception if there is no class for the specified name. NSException *exception = [NSException exceptionWithName:@"com.RMDev.RMSingletonCollector.failed_to_find_class" reason:[NSString stringWithFormat:@"SingletonCollector couldn't find class for name: %@", [className description]] userInfo:nil]; [exception raise]; [exception release]; } return obj; } + (id<RMWeakObjectReference>)referenceForObjectOfType:(NSString *)className identifier:(NSString *)identifier { id obj = [self collectionObjectForType:className identifier:identifier]; RMWeakObjectRef *objectRef = [[RMWeakObjectRef alloc] initWithObject:obj identifier:identifier]; return [objectRef autorelease]; } + (void)destroyCollection { NSDictionary *userInfo = [singletonCollection copy]; [[NSNotificationCenter defaultCenter] postNotificationName:willDestroySingletonCollection object:self userInfo:userInfo]; [userInfo release]; // release the collection and set it to nil. [self setSingletonCollection:nil]; } + (void)destroyCollectionObjectForType:(NSString *)className identifier:(NSString *)identifier { NSString *key; if (identifier) { key = [className stringByAppendingFormat:@".%@", identifier]; } else { key = className; } [[NSNotificationCenter defaultCenter] postNotificationName:willDestroySingletonCollectionObject object:[singletonCollection objectForKey:key] userInfo:nil]; [singletonCollection removeObjectForKey:key]; } @end RMWeakObjectRef.h // // RMWeakObjectRef.h // RMSingletonCollector // // Created by Rich Meade-Miller on 2/12/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // // In order to offset the performance loss from always having to search the dictionary, I made a retainable, weak object reference class. #import <Foundation/Foundation.h> @protocol RMWeakObjectReference <NSObject> @property (nonatomic, assign, readonly) id objectRef; @property (nonatomic, retain, readonly) NSString *className; @property (nonatomic, retain, readonly) NSString *objectIdentifier; @end @interface RMWeakObjectRef : NSObject <RMWeakObjectReference> { id objectRef; NSString *className; NSString *objectIdentifier; } - (RMWeakObjectRef *)initWithObject:(id)object identifier:(NSString *)identifier; - (void)objectWillBeDestroyed:(NSNotification *)notification; @end RMWeakObjectRef.m // // RMWeakObjectRef.m // RMSingletonCollector // // Created by Rich Meade-Miller on 2/12/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import "RMWeakObjectRef.h" #import "RMSingletonCollector.h" @implementation RMWeakObjectRef @dynamic objectRef; @synthesize className, objectIdentifier; - (RMWeakObjectRef *)initWithObject:(id)object identifier:(NSString *)identifier { if (self = [super init]) { NSString *classNameForObject = NSStringFromClass([object class]); className = classNameForObject; objectIdentifier = identifier; objectRef = object; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(objectWillBeDestroyed:) name:willDestroySingletonCollectionObject object:object]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(objectWillBeDestroyed:) name:willDestroySingletonCollection object:[RMSingletonCollector class]]; } return self; } - (id)objectRef { if (objectRef) { return objectRef; } objectRef = [RMSingletonCollector collectionObjectForType:className identifier:objectIdentifier]; return objectRef; } - (void)objectWillBeDestroyed:(NSNotification *)notification { objectRef = nil; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [className release]; [super dealloc]; } @end

    Read the article

< Previous Page | 1 2