Search Results

Search found 134 results on 6 pages for 'nsautoreleasepool'.

Page 4/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • Why is there no autorelease pool when I do performSelectorInBackground: ?

    - by Thanks
    I am calling a method that goes in a background thread: [self performSelectorInBackground:@selector(loadViewControllerWithIndex:) withObject:[NSNumber numberWithInt:viewControllerIndex]]; then, I have this method implementation that gets called by the selector: - (void) loadViewControllerWithIndex:(NSNumber *)indexNumberObj { NSAutoreleasePool *arPool = [[NSAutoreleasePool alloc] init]; NSInteger vcIndex = [indexNumberObj intValue]; Class c; UIViewController *controller = [viewControllers objectAtIndex:vcIndex]; switch (vcIndex) { case 0: c = [MyFirstViewController class]; break; case 1: c = [MySecondViewController class]; break; default: NSLog(@"unknown index for loading view controller: %d", vcIndex); // error break; } if ((NSNull *)controller == [NSNull null]) { controller = [[c alloc] initWithNib]; [viewControllers replaceObjectAtIndex:vcIndex withObject:controller]; [controller release]; } if (controller.view.superview == nil) { UIView *placeholderView = [viewControllerPlaceholderViews objectAtIndex:vcIndex]; [placeholderView addSubview:controller.view]; } [arPool release]; } Althoug I do create an autorelease pool there for that thread, I always get this error: 2009-05-30 12:03:09.910 Demo[1827:3f03] *** _NSAutoreleaseNoPool(): Object 0x523e50 of class NSCFNumber autoreleased with no pool in place - just leaking Stack: (0x95c83f0f 0x95b90442 0x28d3 0x2d42 0x95b96e0d 0x95b969b4 0x93a00155 0x93a00012) If I take away the autorelease pool, I get a whole bunch of messages like these. I also tried to create an autorelease pool around the call of the performSelectorInBackground:, but that doesn't help. I suspect the parameter, but I don't know why the compiler complains about an NSCFNumber. Am I missing something? My Instance variables are all "nonatomic". Can that be a problem? UPDATE: I may also suspect that some variable has been added to an autorelease pool of the main thread (maybe an ivar), and now it trys to release that one inside the wrong autorelease pool? If so, how could I fix that? (damn, this threading stuff is complex ;) )

    Read the article

  • [Cocoa] Placing an NSTimer in a separate thread

    - by ndg
    I'm trying to setup an NSTimer in a separate thread so that it continues to fire when users interact with the UI of my application. This seems to work, but Leaks reports a number of issues - and I believe I've narrowed it down to my timer code. Currently what's happening is that updateTimer tries to access an NSArrayController (timersController) which is bound to an NSTableView in my applications interface. From there, I grab the first selected row and alter its timeSpent column. From reading around, I believe what I should be trying to do is execute the updateTimer function on the main thread, rather than in my timers secondary thread. I'm posting here in the hopes that someone with more experience can tell me if that's the only thing I'm doing wrong. Having read Apple's documentation on Threading, I've found it an overwhelmingly large subject area. NSThread *timerThread = [[[NSThread alloc] initWithTarget:self selector:@selector(startTimerThread) object:nil] autorelease]; [timerThread start]; -(void)startTimerThread { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; activeTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES] retain]; [runLoop run]; [pool release]; } -(void)updateTimer:(NSTimer *)timer { NSArray *selectedTimers = [timersController selectedObjects]; id selectedTimer = [selectedTimers objectAtIndex:0]; NSNumber *currentTimeSpent = [selectedTimer timeSpent]; [selectedTimer setValue:[NSNumber numberWithInt:[currentTimeSpent intValue]+1] forKey:@"timeSpent"]; } -(void)stopTimer { [activeTimer invalidate]; [activeTimer release]; }

    Read the article

  • When memory is actually freeded?

    - by zhyk
    Hello all. I'm trying to understand memory management stuff in Objective-C. If I see the memory usage listed by Activity Monitor, it looks like memory is not being freed (I mean column rsize). But in "Object Allocations" everything looks fine. Here is my simple code: #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSInteger i, k=10000; while (k>0) { NSMutableArray *array = [[NSMutableArray alloc]init]; for (i=0;i<1000*k; i++) { NSString *srtring = [[NSString alloc] initWithString:@"string...."]; [array addObject:srtring]; [srtring release]; srtring = nil; } [array release]; array = nil; k-=500; } [NSThread sleepForTimeInterval:5]; [pool release]; return 0; } As for retain and release it's cool, everything is balanced. But rsize decreases only after quitting from this little program. Is it possible to "clean" memory somehow before quitting?

    Read the article

  • NSOperations or NSThread for bursts of smaller tasks that continuously cancel each other?

    - by RickiG
    Hi I would like to see if I can make a "search as you type" implementation, against a web service, that is optimized enough for it to run on an iPhone. The idea is that the user starts typing a word; "Foo", after each new letter I wait XXX ms. to see if they type another letter, if they don't, I call the web service using the word as a parameter. The web service call and the subsequent parsing of the result I would like to move to a different thread. I have written a simple SearchWebService class, it has only one public method: - (void) searchFor:(NSString*) str; This method tests if a search is already in progress (the user has had a XXX ms. delay in their typing) and subsequently stops that search and starts a new one. When a result is ready a delegate method is called: - (NSArray*) resultsReady; I can't figure out how to get this functionality 'threaded'. If I keep spawning new threads each time a user has a XXX ms. delay in the typing I end up in a bad spot with many threads, especially because I don't need any other search, but the last one. Instead of spawning threads continuously, I have tried keeping one thread running in the background all the time by: - (void) keepRunning { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; SearchWebService *searchObj = [[SearchWebService alloc] init]; [[NSRunLoop currentRunLoop] run]; //keeps it alive [searchObj release]; [pool release]; } But I can't figure out how to access the "searchFor" method in the "searchObj" object, so the above code works and keeps running. I just can't message the searchObj or retrieve the resultReady objects? Hope someone could point me in the right direction, threading is giving me grief:) Thank you.

    Read the article

  • Why does this program take up so much memory?

    - by Adrian
    I am learning Objective-C. I am trying to release all of the memory that I use. So, I wrote a program to test if I am doing it right: #import <Foundation/Foundation.h> #define DEFAULT_NAME @"Unknown" @interface Person : NSObject { NSString *name; } @property (copy) NSString * name; @end @implementation Person @synthesize name; - (void) dealloc { [name release]; [super dealloc]; } - (id) init { if (self = [super init]) { name = DEFAULT_NAME; } return self; } @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Person *person = [[Person alloc] init]; NSString *str; int i; for (i = 0; i < 1e9; i++) { str = [NSString stringWithCString: "Name" encoding: NSUTF8StringEncoding]; person.name = str; [str release]; } [person release]; [pool drain]; return 0; } I am using a mac with snow leopard. To test how much memory this is using, I open Activity Monitor at the same time that it is running. After a couple of seconds, it is using gigabytes of memory. What can I do to make it not use so much?

    Read the article

  • How do I get Spotlight attributes to display in the get info window?

    - by Alexander Rauchfuss
    I have created a spotlight importer for comic files. The attributes are successfully imported and searchable. The one thing that remains is getting the attributes to display in a file's get info window. It seems that this should be a simple matter of editing the schema.xml file so the attributes are nested inside displayattrs tags. Unfortunately this does not seem to be working. I simplified the plugin for testing. The following are all of the important files. schema.xml <types> <type name="cx.c3.cbz-archive"> <allattrs> kMDItemTitle kMDItemAuthors </allattrs> <displayattrs> kMDItemTitle kMDItemAuthors </displayattrs> </type> <type name="cx.c3.cbr-archive"> <allattrs> kMDItemTitle kMDItemAuthors </allattrs> <displayattrs> kMDItemTitle kMDItemAuthors </displayattrs> </type> GetMetadataForFile.m Boolean GetMetadataForFile(void* thisInterface, CFMutableDictionaryRef attributes, CFStringRef contentTypeUTI, CFStringRef pathToFile) { NSAutoreleasePool * pool = [NSAutoreleasePool new]; NSString * file = (NSString *)pathToFile; NSArray * authors = [[UKXattrMetadataStore stringForKey: @"com_opencomics_authors" atPath: file traverseLink: NO] componentsSeparatedByString: @","]; [(NSMutableDictionary *)attributes setObject: authors forKey: (id)kMDItemAuthors]; NSString * title = [UKXattrMetadataStore stringForKey: @"com_opencomics_title" atPath: file traverseLink: NO]; [(NSMutableDictionary *)attributes setObject: title forKey: (id)kMDItemTitle]; [pool release]; return true; }

    Read the article

  • iPhone: Low memory crash...

    - by MacTouch
    Once again I'm hunting memory leaks and other crazy mistakes in my code. :) I have a cache with frequently used files (images, data records etc. with a TTL of about one week and a size limited cache (100MB)). There are sometimes more then 15000 files in a directory. On application exit the cache writes an control file with the current cache size along with other useful information. If the applications crashes for some reason (sh.. happens sometimes) I have in such case to calculate the size of all files on application start to make sure I know the cache size. My app crashes at this point because of low memory and I have no clue why. Memory leak detector does not show any leaks at all. I do not see any too. What's wrong with the code below? Is there any other fast way to calculate the total size of all files within a directory on iPhone? Maybe without to enumerate the whole contents of the directory? The code is executed on the main thread. NSUInteger result = 0; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSDirectoryEnumerator *dirEnum = [[[NSFileManager defaultManager] enumeratorAtPath:path] retain]; int i = 0; while ([dirEnum nextObject]) { NSDictionary *attributes = [dirEnum fileAttributes]; NSNumber* fileSize = [attributes objectForKey:NSFileSize]; result += [fileSize unsignedIntValue]; if (++i % 500 == 0) { // I tried lower values too [pool drain]; } } [dirEnum release]; dirEnum = nil; [pool release]; pool = nil; Thanks, MacTouch

    Read the article

  • Is there a more memory efficient way to search through a Core Data database?

    - by Kristian K
    I need to see if an object that I have obtained from a CSV file with a unique identifier exists in my Core Data Database, and this is the code I deemed suitable for this task: NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity; entity = [NSEntityDescription entityForName:@"ICD9" inManagedObjectContext:passedContext]; [fetchRequest setEntity:entity]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"uniqueID like %@", uniqueIdentifier]; [fetchRequest setPredicate:pred]; NSError *err; NSArray* icd9s = [passedContext executeFetchRequest:fetchRequest error:&err]; [fetchRequest release]; if ([icd9s count] > 0) { for (int i = 0; i < [icd9s count]; i++) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; NSString *name = [[icd9s objectAtIndex:i] valueForKey:@"uniqueID"]; if ([name caseInsensitiveCompare:uniqueIdentifier] == NSOrderedSame && name != nil) { [pool release]; return [icd9s objectAtIndex:i]; } [pool release]; } } return nil; After more thorough testing it appears that this code is responsible for a huge amount of leaking in the app I'm writing (it crashes on a 3GS before making it 20 percent through the 1459 items). I feel like this isn't the most efficient way to do this, any suggestions for a more memory efficient way? Thanks in advance!

    Read the article

  • MAC : How to check if the file is still being copied in cpp?

    - by Peda Pola
    In my current project, we had a requirement to check if the file is still copying. We have already developed a library which will give us OS notification like file_added , file_removed , file_modified, file_renamed on a particular folder along with the corresponding file path. The problem here is that, lets say if you add 1 GB file, it is giving multiple notification such as file_added , file_modified, file_modified as the file is being copied. Now i decided to surpass these notifications by checking if the file is copying or not. Based on that i will ignore events. I have written below code which tells if the file is being copied or not which takes file path as input parameter. Details:- In Mac, while file is being copied the creation date is set as some date less than 1970. Once it is copied the date is set to current date. Am using this technique. Based on this am deciding that file is being copied. Problem:- when we copy file in the terminal it is failing. Please advice me any approach. bool isBeingCopied(const boost::filesystem::path &filePath) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; bool isBeingCopied = false; if([[[[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithUTF8String:filePath.string().c_str()] error:nil] fileCreationDate] timeIntervalSince1970] < 0) { isBeingCopied = true; } [pool release]; return isBeingCopied; }

    Read the article

  • How is an AppDelegate instanciated?

    - by pwny
    I have an iOS application for which I want to create a ViewController programmatically. I started an empty XCode project and modified the main method so it looks like this int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, @"MyAppDelegate_iPad"); [pool release]; return retVal; } The app is a Universal Application, MyAppDelegate_iPad is a subclass of MyAppDelegate, which is a subclass of NSObject <UIApplicationDelegate>. My problem is that the applicationDidFinishLoading method I've overridden in MyAppDelegate_iPad is never called (break point on the first line never hits). The method looks like this -(void) applicationDidFinishLaunching:(UIApplication *)application { window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; if(!window) { [self release]; return; } window.backgroundColor = [UIColor whiteColor]; rootController = [[MyViewController alloc] init]; [window addSubview:rootController.view]; [window makeKeyAndVisible]; [window layoutSubviews]; } I removed the line to link to a nib file from my plist file (I used to get the default "My Universal app on iPad" white screen) and now all that is displayed is a black screen. applicationDidFinishLoading is still not being called. Am I doing something wrong? How should I properly create my AppDelegate instance?

    Read the article

  • Cant access NString after callback in [NSURLConnection sendSynchronousRequest]

    - by John ClearZ
    Hi I am trying to get a cookie from a site which I can do no problem. The problem arises when I try and save the cookie to a NSString in a holder class or anywhere else for that matter and try and access it outside the delegate method where it is first created. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { int i; NSString* c; NSArray* all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://johncleary.net"]]; //NSLog(@"RESPONSE HEADERS: \n%@", [response allHeaderFields]); for (i=0;i<[all count];i++) { NSHTTPCookie* cc = [all objectAtIndex: i]; c = [NSString stringWithFormat: @"%@=%@", [cc name], [cc value]]; [Cookie setCookie: c]; NSLog([Cookie cookie]) // Prints the cookie fine. } [receivedData setLength:0]; } I can see and print the cookie when I am in the method but I cant when trying to access it form anywhere else even though it gets stored in the holder class @interface Cookie : NSObject { NSString* cookie; } + (NSString*) cookie; + (void) setCookie: (NSString*) cookieValue; @end int main (void) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; JCLogin* login; login = [JCLogin new]; [login DoLogin]; NSLog([Cookie cookie]); // Crashes the program [pool drain]; return 0; }

    Read the article

  • Objective C: Function returning correct data for the first time of call and null for other times

    - by Kooshal Bhungy
    Hi all, Am a beginner in objective C, i am implementing a function that would query a web server and display the returning string in console. I am calling the function (getDatafromServer) repeatedly in a loop. The problem is that the first time am getting the value whereas the other times, it returns me a (null) in console... I've searched about memory management and check out on the forums but none have worked. Can you please guys tell me where am wrong in the codes below? Thanks in advance.... @implementation RequestThread +(void)startthread:(id)param{ while (true) { //NSLog(@"Test threads"); sleep(5); NSLog(@"%@",[self getDatafromServer]); } } +(NSString *) getDatafromServer{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *myRequestString = @"name=Hello%20&[email protected]"; NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:@"http://192.168.1.32/gs/includes/widget/getcalls.php?user=asdasd&passw=asdasdasd"]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody: myRequestData]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *myString = [NSString stringWithUTF8String:[returnData bytes]]; [myRequestString release]; [request release]; [returnData release]; return myString; [pool release]; } @end

    Read the article

  • Received memory warning. Level=2, Program received signal: “0”.

    - by sabby
    Hi friends I am getting images from webservice and loading these images in table view.But when i continue to scroll the program receives memory warning level1,level2 and then app exits with status 0.That happens only in device not in simulator. Here is my code which i am putting please help me out. - (void)viewDidLoad { [super viewDidLoad]; UIButton *infoButton = [[UIButton alloc] initWithFrame:CGRectMake(0, -4, 62, 30)]; [infoButton setBackgroundImage:[UIImage imageNamed: @"back.png"] forState:UIControlStateNormal]; [infoButton addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *customBarButtomItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton]; self.navigationItem.leftBarButtonItem = customBarButtomItem; [customBarButtomItem release]; [infoButton release]; UIButton *homeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 62, 30)]; [homeButton setBackgroundImage:[UIImage imageNamed: @"home.png"] forState:UIControlStateNormal]; [homeButton.titleLabel setFont:[UIFont systemFontOfSize:11]]; //[homeButton setTitle:@"UPLOAD" forState:UIControlStateNormal]; [homeButton addTarget:self action:@selector(homeButtonClicked) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *rightBarButtom = [[UIBarButtonItem alloc] initWithCustomView:homeButton]; self.navigationItem.rightBarButtonItem = rightBarButtom; [rightBarButtom release]; [homeButton release]; sellerTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 416) style:UITableViewStylePlain]; sellerTableView.delegate=self; sellerTableView.dataSource=self; sellerTableView.backgroundColor=[UIColor clearColor]; sellerTableView.scrollEnabled=YES; //table.separatorColor=[UIColor grayColor]; //table.separatorColor=[UIColor whiteColor]; //[[table layer]setRoundingMode:NSNumberFormatterRoundDown]; [[sellerTableView layer]setBorderColor:[[UIColor darkGrayColor]CGColor]]; [[sellerTableView layer]setBorderWidth:2]; //[[productTable layer]setCornerRadius:10.3F]; [self.view addSubview:sellerTableView]; appDel = (SnapItAppAppDelegate*)[[UIApplication sharedApplication] delegate]; } -(void)viewWillAppear:(BOOL)animated { spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; spinner.center = self.view.center; [self.view addSubview:spinner]; [spinner startAnimating]; [[SnapItParsing sharedInstance]assignSender:self]; [[SnapItParsing sharedInstance]startParsingForShowProducts:appDel.userIdString]; [sellerTableView reloadData]; } -(void)showProducts:(NSMutableArray*)proArray { if (spinner) { [spinner stopAnimating]; [spinner removeFromSuperview]; [spinner release]; spinner = nil; } if ([[[proArray objectAtIndex:1]objectForKey:@"Success"]isEqualToString:@"True"]) { //[self.navigationController popViewControllerAnimated:YES]; //self.view.alpha=.12; if (productInfoArray) { [productInfoArray release]; } productInfoArray=[[NSMutableArray alloc]init]; for (int i=2; i<[proArray count]; i++) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [productInfoArray addObject:[proArray objectAtIndex:i]]; NSLog(@"data fetch array is====> /n%@",productInfoArray); [pool release]; } } } #pragma mark (tableview methods) - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return 100; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { //return [resultarray count]; return [productInfoArray count]; } -(void)loadImagesInBackground:(NSNumber *)index{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSMutableDictionary *frame = [[productInfoArray objectAtIndex:[index intValue]] retain]; //NSLog(@"frame value ==>%@",[[frame objectForKey:@"Image"]length]); NSString *frameImagePath = [NSString stringWithFormat:@"http://apple.com/snapit/products/%@",[frame objectForKey:@"Image"]]; NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:frameImagePath]]; NSLog(@"FRAME IMAGE%d",[[frame valueForKey:@"Image" ]length]); if([[frame valueForKey:@"Image"] length] == 0){ NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"no_image.png"]; UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; [frame setObject:image forKey:@"friendImage"]; [imagePath release]; //[image release]; } else { //NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:frameImagePath]]; NSLog(@"image data length ==>%d",[imageData length]); if([imageData length] == 0){ NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"no_image.png"]; UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; [frame setObject:image forKey:@"friendImage"]; [imagePath release]; //[image release]; } else { //UIImage *image = [[UIImage alloc] initWithData:imageData]; UIImage *image = [UIImage imageWithData:imageData]; [frame setObject:image forKey:@"friendImage"]; //[image release]; } } [frame release]; frame = nil; [self performSelectorOnMainThread:@selector(reloadTable:) withObject:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[index intValue] inSection:0]] waitUntilDone:NO]; [pool release]; } -(void)reloadTable:(NSArray *)array{ NSLog(@"array ==>%@",array); [sellerTableView reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationNone]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *celltype=@"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:celltype]; for (UIView *view in cell.contentView.subviews) { [view removeFromSuperview]; } if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"] autorelease]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.backgroundColor=[UIColor clearColor]; //cell.textLabel.text=[[resultarray objectAtIndex:indexPath.row] valueForKey:@"Service"]; /*UIImage *indicatorImage = [UIImage imageNamed:@"indicator.png"]; cell.accessoryView = [[[UIImageView alloc] initWithImage:indicatorImage] autorelease];*/ /*NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector() object:nil]; [thread setStackSize:44]; [thread start];*/ cell.backgroundView=[[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"cell.png"]]autorelease]; // [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back.png"]] autorelease]; cell.selectionStyle=UITableViewCellSelectionStyleNone; } UIImageView *imageView= [[UIImageView alloc] initWithFrame:CGRectMake(19, 15, 75, 68)]; imageView.contentMode = UIViewContentModeScaleToFill; // @synchronized(self) //{ NSMutableDictionary *dict = [productInfoArray objectAtIndex:indexPath.row]; if([dict objectForKey:@"friendImage"] == nil){ imageView.backgroundColor = [UIColor clearColor]; if ([dict objectForKey:@"isThreadLaunched"] == nil) { [NSThread detachNewThreadSelector:@selector(loadImagesInBackground:) toTarget:self withObject:[NSNumber numberWithInt:indexPath.row]]; [dict setObject:@"Yes" forKey:@"isThreadLaunched"]; } }else { imageView.image =[dict objectForKey:@"friendImage"]; } //NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"no_image.png"]; //imageView.layer.cornerRadius = 20.0;//vk //imageView.image=[UIImage imageWithContentsOfFile:imagePath]; //imageView.layer.masksToBounds = YES; //imageView.layer.borderColor = [UIColor darkGrayColor].CGColor; //imageView.layer.borderWidth = 1.0;//vk //imageView.layer.cornerRadius=7.2f; [cell.contentView addSubview:imageView]; //[imagePath release]; [imageView release]; imageView = nil; //} UILabel *productCodeLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 7, 60,20 )]; productCodeLabel.textColor = [UIColor whiteColor]; productCodeLabel.backgroundColor=[UIColor clearColor]; productCodeLabel.text=[NSString stringWithFormat:@"%@",@"Code"]; [cell.contentView addSubview:productCodeLabel]; [productCodeLabel release]; UILabel *CodeValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(170, 7, 140,20 )]; CodeValueLabel.textColor = [UIColor whiteColor]; CodeValueLabel.backgroundColor=[UIColor clearColor]; CodeValueLabel.text=[NSString stringWithFormat:@"%@",[[productInfoArray objectAtIndex:indexPath.row]valueForKey:@"ID"]]; [cell.contentView addSubview:CodeValueLabel]; [CodeValueLabel release]; UILabel *productNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 35, 60,20 )]; productNameLabel.textColor = [UIColor whiteColor]; productNameLabel.backgroundColor=[UIColor clearColor]; productNameLabel.text=[NSString stringWithFormat:@"%@",@"Name"]; [cell.contentView addSubview:productNameLabel]; [productNameLabel release]; UILabel *NameValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(170, 35, 140,20 )]; NameValueLabel.textColor = [UIColor whiteColor]; NameValueLabel.backgroundColor=[UIColor clearColor]; NameValueLabel.text=[NSString stringWithFormat:@"%@",[[productInfoArray objectAtIndex:indexPath.row]valueForKey:@"Title"]]; [cell.contentView addSubview:NameValueLabel]; [NameValueLabel release]; UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 68, 60,20 )]; dateLabel.textColor = [UIColor whiteColor]; dateLabel.backgroundColor=[UIColor clearColor]; dateLabel.text=[NSString stringWithFormat:@"%@",@"Date"]; [cell.contentView addSubview:dateLabel]; [dateLabel release]; UILabel *dateValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(170, 68, 140,20 )]; dateValueLabel.textColor = [UIColor whiteColor]; dateValueLabel.backgroundColor=[UIColor clearColor]; dateValueLabel.text=[NSString stringWithFormat:@"%@",[[productInfoArray objectAtIndex:indexPath.row]valueForKey:@"PostedDate"]]; dateValueLabel.font=[UIFont systemFontOfSize:14]; dateValueLabel.numberOfLines=3; dateValueLabel.adjustsFontSizeToFitWidth=YES; [dateValueLabel setLineBreakMode:UILineBreakModeCharacterWrap]; [cell.contentView addSubview:dateValueLabel]; [dateValueLabel release]; } Please-2 help me out ,where i am doing mistake.....

    Read the article

  • "for" loop from program 7.6 from Kochan's "Programming in Objective-C"

    - by Mr_Vlasov
    "The sigma notation is shorthand for a summation. Its use here means to add the values of 1/2^i, where i varies from 1 to n. That is, add 1/2 + 1/4 + 1/8 .... If you make the value of n large enough, the sum of this series should approach 1. Let’s experiment with different values for n to see how close we get." #import "Fraction.h" int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *aFraction = [[Fraction alloc] init]; Fraction *sum = [[Fraction alloc] init], *sum2; int i, n, pow2; [sum setTo: 0 over: 1]; // set 1st fraction to 0 NSLog (@"Enter your value for n:"); scanf ("%i", &n); pow2 = 2; for (i = 1; i <= n; ++i) { [aFraction setTo: 1 over: pow2]; sum2 = [sum add: aFraction]; [sum release]; // release previous sum sum = sum2; pow2 *= 2; } NSLog (@"After %i iterations, the sum is %g", n, [sum convertToNum]); [aFraction release]; [sum release]; [pool drain]; return 0; } Question: Why do we have to create additional variable sum2 that we are using in the "for" loop? Why do we need "release previous sum" here and then again give it a value that we just released? : sum2 = [sum add: aFraction]; [sum release]; // release previous sum sum = sum2; Is it just for the sake of avoiding memory leakage? (method "add" initializes a variable that is stored in sum2)

    Read the article

  • memory management: am i doing something wrong here?

    - by z s
    Hi, In a very small number of cases in my iphone app, I get a crash after the for loop in the code below: ABAddressBookRef addressBookInit = ABAddressBookCreate(); CFMutableArrayRef abContacts = (CFMutableArrayRef)ABAddressBookCopyArrayOfAllPeople(addressBookInit); // get array of all contacts CFArraySortValues (abContacts, CFRangeMake(0, CFArrayGetCount(abContacts)), (CFComparatorFunction)ABPersonComparePeopleByName, (void *)ABPersonGetSortOrdering()); NSArray *copypeople = (NSArray *) abContacts; NSMutableArray *tempTheadlist = [[NSMutableArray alloc] init]; for (int i=0; i < copypeople.count; i++) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; ABRecordRef record = [copypeople objectAtIndex:i]; if (blah blah) [tempThreadList addObject: someObject]; [pool release]; } // POINT OF CRASH AFTER LOOP ENDS if (tempTheadlist.count > 0) [NSThread detachNewThreadSelector: @selector(loading_pictures:) toTarget:self withObject:tempTheadlist]; [tempTheadlist release]; [copypeople release]; CFRelease(addressBookInit); Any reason why it should crash at any point here?

    Read the article

  • Application is crash..

    - by user338322
    Below is my crash Report. 0 0x326712f8 in prepareForMethodLookup () 1 0x3266cf5c in lookUpMethod () 2 0x32668f28 in objc_msgSend_uncached () 3 0x33f70996 in NSPopAutoreleasePool () 4 0x33f82a6c in -[NSAutoreleasePool drain] () 5 0x00003d3e in -[CameraViewcontroller save:] (self=0x811400, _cmd=0x319c00d4, number=0x11e210) at /Users/hardikrathore/Desktop/LiveVideoRecording/Classes/CameraViewcontroller.m:266 6 0x33f36f8a in __NSFireDelayedPerform () 7 0x32da44c2 in CFRunLoopRunSpecific () 8 0x32da3c1e in CFRunLoopRunInMode () 9 0x31bb9374 in GSEventRunModal () 10 0x30bf3c30 in -[UIApplication _run] () 11 0x30bf2230 in UIApplicationMain () 12 0x00002650 in main (argc=1, argv=0x2ffff474) at /Users/hardikrathore/Desktop/LiveVideoRecording/main.m:14 And this is the code. lines, where I am getting the error. -(void)save:(id)number { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; j =[number intValue]; while(screens[j] != NULL){ NSLog(@" image made : %d",j); UIImage * image = [UIImage imageWithCGImage:screens[j]]; image=[self imageByCropping:image toRect:CGRectMake(0, 0, 320, 240)]; NSData *imgdata = UIImageJPEGRepresentation(image,0.3); [image release]; CGImageRelease(screens[j]); screens[j] = NULL; UIImage * image1 = [UIImage imageWithCGImage:screens[j+1]]; image1=[self imageByCropping:image1 toRect:CGRectMake(0, 0, 320, 240)]; NSData *imgdata1 = UIImageJPEGRepresentation(image1,0.3); [image1 release]; CGImageRelease(screens[j+1]); screens[j+1] = NULL; NSString *urlString=@"http://www.test.itmate4.com/iPhoneToServerTwice.php"; // setting up the request object now NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *fileName=[VideoID stringByAppendingString:@"_"]; fileName=[fileName stringByAppendingString:[NSString stringWithFormat:@"%d",k]]; NSString *fileName2=[VideoID stringByAppendingString:@"_"]; fileName2=[fileName2 stringByAppendingString:[NSString stringWithFormat:@"%d",k+1]]; /* add some header info now we always need a boundary when we post a file also we need to set the content type You might want to generate a random boundary.. this is just the same as my output from wireshark on a valid html post */ NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"]; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; /* now lets create the body of the post */ //NSString *count=[NSString stringWithFormat:@"%d",front];; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; //[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; count=\"@\"";filename=\"%@.jpg\"\r\n",count,fileName] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n",fileName] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imgdata]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; //second boundary NSString *string1 = [[NSString alloc] initWithFormat:@"\r\n--%@\r\n",boundary]; NSString *string2 =[[NSString alloc] initWithFormat:@"Content-Disposition: form-data; name=\"userfile2\"; filename=\"%@.jpg\"\r\n",fileName2]; NSString *string3 =[[NSString alloc] initWithFormat:@"\r\n--%@--\r\n",boundary]; [body appendData:[string1 dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[string2 dataUsingEncoding:NSUTF8StringEncoding]]; //experiment //[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile2\"; filename=\"%@.jpg\"\r\n",fileName2] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imgdata1]]; //[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[string3 dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the reqeust [request setHTTPBody:body]; // now lets make the connection to the web NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; if([returnString isEqualToString:@"SUCCESS"]) { NSLog(returnString); k=k+2; j=j+2; [self performSelectorInBackground:@selector(save:) withObject:(id)[NSNumber numberWithInt:j]]; } //k=k+2; [imgdata release]; [imgdata1 release]; [NSThread sleepForTimeInterval:.01]; } [pool drain]; <-------------Line 266 } As you can see in log report. I am getting the error, Line 266. Some autorelease problem Any help !!!? coz I am not getting why its happening.

    Read the article

  • Which of these algorithms is best for my goal?

    - by JonathonG
    I have created a program that restricts the mouse to a certain region based on a black/white bitmap. The program is 100% functional as-is, but uses an inaccurate, albeit fast, algorithm for repositioning the mouse when it strays outside the area. Currently, when the mouse moves outside the area, basically what happens is this: A line is drawn between a pre-defined static point inside the region and the mouse's new position. The point where that line intersects the edge of the allowed area is found. The mouse is moved to that point. This works, but only works perfectly for a perfect circle with the pre-defined point set in the exact center. Unfortunately, this will never be the case. The application will be used with a variety of rectangles and irregular, amorphous shapes. On such shapes, the point where the line drawn intersects the edge will usually not be the closest point on the shape to the mouse. I need to create a new algorithm that finds the closest point to the mouse's new position on the edge of the allowed area. I have several ideas about this, but I am not sure of their validity, in that they may have far too much overhead. While I am not asking for code, it might help to know that I am using Objective C / Cocoa, developing for OS X, as I feel the language being used might affect the efficiency of potential methods. My ideas are: Using a bit of trigonometry to project lines would work, but that would require some kind of intense algorithm to test every point on every line until it found the edge of the region... That seems too resource intensive since there could be something like 200 lines that would have each have to have as many as 200 pixels checked for black/white.... Using something like an A* pathing algorithm to find the shortest path to a black pixel; however, A* seems resource intensive, even though I could probably restrict it to only checking roughly in one direction. It also seems like it will take more time and effort than I have available to spend on this small portion of the much larger project I am working on, correct me if I am wrong and it would not be a significant amount of code (100 lines or around there). Mapping the border of the region before the application begins running the event tap loop. I think I could accomplish this by using my current line-based algorithm to find an edge point and then initiating an algorithm that checks all 8 pixels around that pixel, finds the next border pixel in one direction, and continues to do this until it comes back to the starting pixel. I could then store that data in an array to be used for the entire duration of the program, and have the mouse re-positioning method check the array for the closest pixel on the border to the mouse target position. That last method would presumably execute it's initial border mapping fairly quickly. (It would only have to map between 2,000 and 8,000 pixels, which means 8,000 to 64,000 checked, and I could even permanently store the data to make launching faster.) However, I am uncertain as to how much overhead it would take to scan through that array for the shortest distance for every single mouse move event... I suppose there could be a shortcut to restrict the number of elements in the array that will be checked to a variable number starting with the intersecting point on the line (from my original algorithm), and raise/lower that number to experiment with the overhead/accuracy tradeoff. Please let me know if I am over thinking this and there is an easier way that will work just fine, or which of these methods would be able to execute something like 30 times per second to keep mouse movement smooth, or if you have a better/faster method. I've posted relevant parts of my code below for reference, and included an example of what the area might look like. (I check for color value against a loaded bitmap that is black/white.) // // This part of my code runs every single time the mouse moves. // CGPoint point = CGEventGetLocation(event); float tX = point.x; float tY = point.y; if( is_in_area(tX,tY, mouse_mask)){ // target is inside O.K. area, do nothing }else{ CGPoint target; //point inside restricted region: float iX = 600; // inside x float iY = 500; // inside y // delta to midpoint between iX,iY and tX,tY float dX; float dY; float accuracy = .5; //accuracy to loop until reached do { dX = (tX-iX)/2; dY = (tY-iY)/2; if(is_in_area((tX-dX),(tY-dY),mouse_mask)){ iX += dX; iY += dY; } else { tX -= dX; tY -= dY; } } while (abs(dX)>accuracy || abs(dY)>accuracy); target = CGPointMake(roundf(tX), roundf(tY)); CGDisplayMoveCursorToPoint(CGMainDisplayID(),target); } Here is "is_in_area(int x, int y)" : bool is_in_area(NSInteger x, NSInteger y, NSBitmapImageRep *mouse_mask){ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSUInteger pixel[4]; [mouse_mask getPixel:pixel atX:x y:y]; if(pixel[0]!= 0){ [pool release]; return false; } [pool release]; return true; }

    Read the article

  • How do I upload an NSImage(NSData)to Twitpic with OAMutableURLRequest?

    - by timothy5216
    I'm using OAConsumer in my xAuth twitterEngine and i'm adding Twitpic OAuth Echo to it. But it won't POST the NSData. here is some of my code: //other file NSArray *reps = [[imageToUpload image] representations]; NSData *imageData = [NSBitmapImageRep representationOfImageRepsInArray:reps usingType:NSJPEGFileType properties:nil]; [twitter testUploadImageData:imageData withMessage:@"Hello WORLD!!" toURL:[NSURL URLWithString:uploadURL.stringValue]]; // - (void)testUploadImageData:(NSData *)data withMessage:(NSString *)message toURL:(NSURL *)url; { //url = @"http://api.twitpic.com/2/upload.xml" //message = @"Hello WORLD!!" NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *String = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSLog(@"dataString: %@",String); OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url consumer:self.consumer token:_accessToken realm:nil signatureProvider:nil]; // Setup POST body [request setHTTPMethod:@"POST"]; //NSString *stringBoundary = [NSString stringWithString:@"0xKhTmLbOuNdArY"]; //NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", stringBoundary]; // NSString *stringBoundarySeparator = [NSString stringWithFormat:@"\r\n--%@\r\n", stringBoundary]; /* NSMutableString *postString = [NSMutableString string]; [postString appendString:@"\r\n"]; [postString appendString:stringBoundarySeparator]; [postString appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"message\"\r\n\r\n%@", message]]; [postString appendString:stringBoundarySeparator]; [postString appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"media\"; filename=\"%@\"\r\n", @"file.jpg"]]; [postString appendString:@"Content-Type: image/jpg\r\n"]; [postString appendString:@"Content-Transfer-Encoding: binary\r\n\r\n"]; // Setting up the POST request's multipart/form-data body NSMutableData *postBody = [NSMutableData data]; [postBody appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:data]; [request setHTTPBody:postBody]; */ [request setHTTPMethod:@"POST"]; NSString *thing = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSLog(@"%@",thing); [request setParameters:[NSArray arrayWithObjects: [OARequestParameter requestParameterWithName:@"oauth_token" value:_accessToken.key], [OARequestParameter requestParameterWithName:@"X-Auth-Service-Provider" value:@"https://api.twitter.com/1/account/verify_credentials.json"], [OARequestParameter requestParameterWithName:@"key" value:@"my-key-here :P"], [OARequestParameter requestParameterWithName:@"message" value:message], //iv'e changed this many times. I was just trying this to see if it works [OARequestParameter requestParameterWithName:@"media" value:thing], nil]]; OAAsynchronousDataFetcher *dataFetcher = [[OAAsynchronousDataFetcher alloc] init]; [dataFetcher initWithRequest:request delegate:self didFinishSelector:@selector(uploadDidUpload:withData:) didFailSelector:@selector(uploadDidFail:withData:)]; [dataFetcher start]; [dataFetcher release]; [request release]; [pool drain]; } I'm authenticated but it still won't POST the data :(

    Read the article

  • Why does my UIActivityIndicatorView only display once?

    - by Schwigg
    I'm developing an iPhone app that features a tab-bar based navigation with five tabs. Each tab contains a UITableView whose data is retrieved remotely. Ideally, I would like to use a single UIActivityIndicatorView (a subview of the window) that is started/stopped during this remote retrieval - once per tab. Here's how I set up the spinner in the AppDelegate: - (void)applicationDidFinishLaunching:(UIApplication *)application { [window addSubview:rootController.view]; activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; [activityIndicator setCenter:CGPointMake(160, 200)]; [window addSubview:activityIndicator]; [window makeKeyAndVisible]; } Since my tabs were all performing a similiar function, I created a base class that all of my tabs' ViewControllers inherit from. Here is the method I'm using to do the remote retrieval: - (void)parseXMLFileAtURL:(NSString *)URL { NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init]; AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; NSLog(@"parseXMLFileAtURL started."); [appDelegate.activityIndicator startAnimating]; NSLog(@"appDelegate.activityIndicator: %@", appDelegate.activityIndicator); articles = [[NSMutableArray alloc] init]; NSURL *xmlURL = [NSURL URLWithString:URL]; rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; [rssParser setDelegate:self]; [rssParser setShouldProcessNamespaces:NO]; [rssParser setShouldReportNamespacePrefixes:NO]; [rssParser setShouldResolveExternalEntities:NO]; [rssParser parse]; NSLog(@"parseXMLFileAtURL finished."); [appDelegate.activityIndicator stopAnimating]; [apool release]; } This method is being called by each view controller as follows: - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if ([articles count] == 0) { NSString *path = @"http://www.myproject.com/rss1.xml"; [self performSelectorInBackground:@selector(parseXMLFileAtURL:) withObject:path]; } } This works great while the application loads the first tab's content. I'm presented with the empty table and the spinner. As soon as the content loads, the spinner goes away. Strangely, when I click the second tab, the NSLog messages from the -parseXMLFileAtURL: method show up in the log, but the screen hangs on the first tab's view and I do not see the spinner. As soon as the content is done downloading, the second tab's view appears. I suspect this has something to do with threading, with which I'm still becoming acquainted. Am I doing something obviously wrong here?

    Read the article

  • I get EXC_BAD_ACCESS when MaxConcurrentOperationCount > 1

    - by kudorgyozo
    Hello i am using NSOperationQueue to download images in the background. I have created a custom NSOperation to download the images. I put the images in table cells. The problem is if I do [operationQueue setMaxConcurrentOperationCount: 10] and i scroll down several cells the program crashes with EXC_BAD_ACCESS. Every time it crashes at the same place in the table. There are 3 cells one after the other which are for the same company and have the same logo so basically it should download the images 3 times. Every other time it works fine. - (void) main { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSURL *url = [[NSURL alloc] initWithString:self.imageURL]; debugLog(@"downloading image: %@", self.imageURL); //NSError *error = nil; NSData *data = [[NSData alloc] initWithContentsOfURL:url]; [url release]; UIImage *image = [[UIImage alloc] initWithData:data]; [data release]; if (image) { if (image.size.width != ICONWIDTH && image.size.height != ICONHEIGHT) { UIImage *resizedImage; CGSize itemSize = CGSizeMake(ICONWIDTH, ICONHEIGHT); UIGraphicsBeginImageContext(itemSize); CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height); [image drawInRect:imageRect]; resizedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); self.theImage = resizedImage; } else { self.theImage = image; } [image release]; } [delegate didFinishDownloadingImage: self]; [pool release]; } This is how i handle downloading the images. If i comment out [delegate didFinishDownloadingImage: self]; in the function above it doesn't crash but of course it is useless. -(void) didFinishDownloadingImage:(ImageDownloadOperation *) imageDownloader { [self performSelectorOnMainThread: @selector(handleDidFinishDownloadingImage:) withObject: imageDownloader waitUntilDone: FALSE]; } -(void) handleDidFinishDownloadingImage:(ImageDownloadOperation *)imageDownloadOperation { NSArray *visiblePaths = [self.myTableView indexPathsForVisibleRows]; CompanyImgDownloaderState *stateObject = (CompanyImgDownloaderState *)[imageDownloadOperation stateObject]; if ([visiblePaths containsObject: stateObject.indexPath]) { //debugLog(@"didFinishDownloadingImage %@ %@", imageDownloader.theImage); UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath: stateObject.indexPath]; UIImageView *imageView = (UIImageView *)[cell viewWithTag: 1]; if (imageDownloadOperation.theImage) { imageView.image = imageDownloadOperation.theImage; stateObject.company.icon = imageDownloadOperation.theImage; } else { imageView.image = [(TestWebServiceAppDelegate *)[[UIApplication sharedApplication] delegate] getCylexIcon]; stateObject.company.icon = [(TestWebServiceAppDelegate *)[[UIApplication sharedApplication] delegate] getCylexIcon]; } } }

    Read the article

  • Problems with makeObjectsPerformSelector inside and outside a class?

    - by QuakAttak
    A friend and I are creating a card game for the iPhone, and in these early days of the project, I'm developing a Deck class and a Card class to keep up with the cards. I'm wanting to test the shuffle method of the Deck class, but I am not able to show the values of the cards in the Deck class instance. The Deck class has a NSArray of Card objects that have a method called displayCard that shows the value and suit using console output(printf or NSLog). In order to show what cards are in a Deck instance all at once, I am using this, [deck makeObjectsPerformSelector:@selector(displayCard)], where deck is the NSArray in the Deck class. Inside of the Deck class, nothing is displayed on the console output. But in a test file, it works just fine. Here's the test file that creates its own NSArray: #import <Foundation/Foundation.h> #import "card.h" int main (int argc, char** argv) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; Card* two = [[Card alloc] initValue:2 withSuit:'d']; Card* three = [[Card alloc] initValue:3 withSuit:'h']; Card* four = [[Card alloc] initValue:4 withSuit:'c']; NSArray* deck = [NSArray arrayWithObjects:two,three,four,nil]; //Ok, what if we release the objects in the array before they're used? //I don't think this will work... [two release]; [three release]; [four release]; //Ok, it works... I wonder how... //Hmm... how will this work? [deck makeObjectsPerformSelector:@selector(displayCard)]; //Yay! It works fine! [pool release]; return 0; } This worked beautifully, so I created an initializer around this idea, creating 52 card objects one at a time and adding them to the NSArray using deck = [deck arrayByAddingObject:newCard]. Is the real problem with how I'm using makeObjectsPerformSelector or something before/after it?

    Read the article

  • iphone initializing tab bar controller view programatically

    - by unsorted
    I want to initialize my tab bar controller programatically, but I just get a blank screen with the code I have. I tried to imitate TheElements sample app, and stuff seems comparable going line-by-line, but obviously something's wrong. Any suggestions? Thanks... In main.m: #import <UIKit/UIKit.h> int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, @"DubbleWrapAppDelegate"); [pool release]; return retVal; } In DubbleWrapAppDelegate.h: @interface DubbleWrapAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> { UIWindow *window; UITabBarController *tabBarController; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UITabBarController *tabBarController; @end In DubbleWrapAppDelegate.m: @implementation DubbleWrapAppDelegate @synthesize window; @synthesize tabBarController; - init { if (self = [super init]){ // initialize to nil window = nil; tabBarController = nil; } return self; } - (void)applicationDidFinishLaunching:(UIApplication *)application { SafeTableViewController *vc1 = [[SafeTableViewController alloc] initWithStyle:UITableViewStylePlain]; [vc1 setSafeItems:[SafeItem knownSafeItems]]; // Set the list of known SafeItems: UINavigationController *nc1; nc1 = [[UINavigationController alloc] initWithRootViewController:vc1]; [vc1 release]; BoxXRayTableViewController *vc2 = [[BoxXRayTableViewController alloc] initWithStyle:UITableViewStylePlain]; UINavigationController *nc2; nc2 = [[UINavigationController alloc] initWithRootViewController:vc2]; [vc2 release]; AboutLibertyViewController *vc3 = [[AboutLibertyViewController alloc] init]; UINavigationController *nc3; nc3 = [[UINavigationController alloc] initWithRootViewController:vc3]; [vc3 release]; NSArray* controllers = [NSArray arrayWithObjects:nc1, nc2, nc3, nil]; tabBarController = [[UITabBarController alloc] init]; tabBarController.viewControllers = controllers; [controllers release]; // Add the tab bar controller's current view as a subview of the window window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; [window setBackgroundColor:[UIColor redColor]]; [window addSubview:tabBarController.view]; [window makeKeyAndVisible]; [nc1 release]; [nc2 release]; [nc3 release]; } The plist is set so that there is no NIB file referenced.

    Read the article

  • Drawing performance with CGImageCreateWithJPEGDataProvider?

    - by Rnegi
    I've actually curious about this for the iPhone. I am getting an MJPEG stream from a server and trying to render it natively on the iphone (without the use of safari class). Reasons for this is because the safari class while CAN render MJPEG natively, does not do so at the framerate I would like. So I tried drawing it natively, but I've come up with performance issues, namely a syncing issue between what I'm getting from the server and what I am able to draw onto the screen of the phone. (There should be a little lag, but the drift gets really bad, which is what I want to avoid). So I have a connection set up to my server and I do get the JPEGS. It's just data I insert into a NSMutableArray buffer CFMutableDataRef _t_data_ref = (CFMutableDataRef)[_buffer_array objectAtIndex:0]; //CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData (_cf_buffer_data); CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData(_t_data_ref); CGImageRef image = CGImageCreateWithJPEGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault); CGImageRef imgRef = image; CGContextDrawImage(context, CGRectMake(0, 17, 380, 285), imgRef); CGImageRelease(image); CGDataProviderRelease(imgDataProvider); please note this is the gist of my code, but it should summarize what I am trying to accomplish with regards to drawing. Also in order to get the framerate in sync, I had to detach a separate thread that sleeps X seconds and calls [self setNeedsDisplay]. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Top-level pool while(1) { //[NSThread sleepForTimeInterval:TIMER_REFRESH_VALUE]; //sleep(unsigned int ); usleep(MICRO_REFRESH_VALUE); if ([_buffer_array count] > 10) { //NSLog(@"stuff %d", [_buffer_array count]); //[self setNeedsDisplay]; [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:NO]; } } [pool release]; // Release the objects in the pool. My buffer of jpeg data actually fills up quite quick, but I can't seem to actually consume what i'm getting at the same rate, actually much slower. Are there any documents that can describe what kind of performance tuning I can do to make it go faster when rendering the JPEG to the screen? Or am I kind of stuck here? Thanks!

    Read the article

  • 'object' undeclared <first use in this function>

    - by Mohit Deshpande
    I am using Winchain to develop on my Windows 7 machine. Here is my code: iPhoneTest.h #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface iPhoneTest : UIApplication { UITextView *textview; UIView *mainView; } @end iPhoneTest.m #import "iPhoneTest.h" #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> #import <CoreFoundation/CoreFoundation.h> @implementation iPhoneTest -(void)applicationDidFinishLaunching:(id)unused { UIWindow *window; struct CGRect rect = [UIHardware fullScreenApplicationContentRect]; rect.origin.x = rect.origin.y = 0.0f; window = [[UIWindow alloc] initWithContentRect: rect]; mainView = [[UIView alloc] initWithFrame: rect]; textView = [[UITextView alloc] init]; [textView setEditable:YES]; [textView setTextSize:14]; [window orderFront: self]; [window makeKey: self]; [window _setHidden: NO]; [window setContentView: mainView]; [mainView addSubview:textView]; [textView setText:@"Hello World"]; } @end main.m #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "iPhoneTest.h" int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int ret = UIApplicationMain(argc, argv, [iPhoneTest class]); [pool release]; return ret; } Makefile INFOPLIST_FILE=Info.plist SOURCES=\ main.m \ iPhoneTest.m CC=/usr/local/bin/arm-apple-darwin-gcc CFLAGS=-g -O2 -Wall LD=$(CC) LDFLAGS=-lobjc -framework CoreFoundation -framework Foundation -framework UIKit -framework LayerKit PRODUCT_NAME=iPhoneTest SRCROOT=/iphone-apps/iPhoneTest WRAPPER_NAME=$(PRODUCT_NAME).app EXECUTABLE_NAME=$(PRODUCT_NAME) SOURCES_ABS=$(addprefix $(SRCROOT)/,$(SOURCES)) INFOPLIST_ABS=$(addprefix $(SRCROOT)/,$(INFOPLIST_FILE)) OBJECTS=\ $(patsubst %.c,%.o,$(filter %.c,$(SOURCES))) \ $(patsubst %.cc,%.o,$(filter %.cc,$(SOURCES))) \ $(patsubst %.cpp,%.o,$(filter %.cpp,$(SOURCES))) \ $(patsubst %.m,%.o,$(filter %.m,$(SOURCES))) \ $(patsubst %.mm,%.o,$(filter %.mm,$(SOURCES))) OBJECTS_ABS=$(addprefix $(CONFIGURATION_TEMP_DIR)/,$(OBJECTS)) APP_ABS=$(BUILT_PRODUCTS_DIR)/$(WRAPPER_NAME) PRODUCT_ABS=$(APP_ABS)/$(EXECUTABLE_NAME) all: $(PRODUCT_ABS) $(PRODUCT_ABS): $(APP_ABS) $(OBJECTS_ABS) $(LD) $(LDFLAGS) -o $(PRODUCT_ABS) $(OBJECTS_ABS) $(APP_ABS): $(INFOPLIST_ABS) mkdir -p $(APP_ABS) cp $(INFOPLIST_ABS) $(APP_ABS)/ $(CONFIGURATION_TEMP_DIR)/%.o: $(SRCROOT)/%.m mkdir -p $(dir $@) $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ clean: echo rm -f $(OBJECTS_ABS) echo rm -rf $(APP_ABS) When I try to compile it with make, I get iPhoneTest.m: In fucntion '-[iPhoneTest applicationDidFinishLaunching:]' iPhoneTest.m:15: error: 'testView' undeclared <first use in this function> iPhoneTest.m:15: error: <Each undeclared identifier is reported only once for each function it appears in> Can anyone spot the problem?

    Read the article

  • What could cause this difference in behaviour from iphone OS3.0 to iOS4.0?

    - by frankodwyer
    I am getting a strange EXC_BAD_ACCESS error when running my app on iOS4. The app has been pretty solid on OS3.x for some time - not even seeing crash logs in this area of the code (or many at all) in the wild. I've tracked the error down to this code: main class: - (void) sendPost:(PostRequest*)request { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSURLResponse* response; NSError* error; NSData *serverReply = [NSURLConnection sendSynchronousRequest:request.request returningResponse:&response error:&error]; ServerResponse* serverResponse=[[ServerResponse alloc] initWithResponse:response error:error data:serverReply]; [request.objectToNotifyWhenDone performSelectorOnMainThread:request.targetToNotifyWhenDone withObject:serverResponse waitUntilDone:YES]; [pool drain]; } (Note: sendPost is run on a separate thread for each invocation of it. PostRequest is just a class to encapsulate a request and a selector to notify when complete) ServerResponse.m: @synthesize response; @synthesize replyString; @synthesize error; @synthesize plist; - (ServerResponse*) initWithResponse:(NSURLResponse*)resp error:(NSError*)err data:(NSData*)serverReply { self.response=resp; self.error=err; self.plist=nil; self.replyString=nil; if (serverReply) { self.replyString = [[[NSString alloc] initWithBytes:[serverReply bytes] length:[serverReply length] encoding: NSASCIIStringEncoding] autorelease]; NSPropertyListFormat format; NSString *errorStr; plist = [NSPropertyListSerialization propertyListFromData:serverReply mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorStr]; } return self; } ServerResponse.h: @property (nonatomic, retain) NSURLResponse* response; @property (nonatomic, retain) NSString* replyString; @property (nonatomic, retain) NSError* error; @property (nonatomic, retain) NSDictionary* plist; - (ServerResponse*) initWithResponse:(NSURLResponse*)response error:(NSError*)error data:(NSData*)serverReply; This reliably crashes with a bad access in the line: self.error=err; ...i.e. in the synthesized property setter! I'm stumped as to why this should be, given the code worked on the previous OS and hasn't changed since (even the binary compiled with the previous SDK crashes the same way, but not on OS3.0) - and given it is a simple property method. Any ideas? Could the NSError implementation have changed between releases or am I missing something obvious?

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >