Search Results

Search found 1559 results on 63 pages for 'nslog'.

Page 11/63 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • how to get IndexPath

    - by user145883
    in iphone application. I'm trying to get indexPath.row value to do something on the basis of row selected in programmatically created tableview. Can someone please tell me why is the indexPath.row value is not coming correct. It's some thing like 21487...3? NSUInteger nSections = [myTableView numberOfSections]; NSUInteger nRows = [myTableView numberOfRowsInSection:nSections]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow: nRows inSection:nSections]; NSLog(@"No of sections in my table view %d",nSections); NSLog(@"No of rows in my table view %d",nRows); NSLog(@"Value of selected indexPath Row %d", indexPath.row); Thanks, Aaryan

    Read the article

  • Cocos2dx InApp Purchase for ios

    - by Ahmad dar
    I am trying to integrate In App Purchases in my app made by using cocos2d x c++. I am using easyNdk Helper for In App Purchases. My In App Purchases works perfectly for my Objective C apps. But for cocos2d x it is throwing error for the following line if ([[RageIAPHelper sharedInstance] productPurchased:productP.productIdentifier]) Actually value came from CPP file perfectly in form of arguments and Properly shows their value in NSLog , But it always shows the objects as nil even objetcs print their stored value in NSLog also @try catch condition is not working and finally throw the following error Please Help me what i have to do ? Thanks

    Read the article

  • How To show document directory save image in thumbnail in cocos2d class

    - by Anil gupta
    I have just implemented multiple photo selection from iphone photo library and i am saving all selected photo in document directory every time as a array, now i want to show all saved images in my class from document directory as a thumbnail, i have tried some logic but my game getting crashing, My code is below. Any help will be appreciate. Thanks in advance. -(id) init { // always call "super" init // Apple recommends to re-assign "self" with the "super" return value if( (self=[super init])) { CCSprite *photoalbumbg = [CCSprite spriteWithFile:@"photoalbumbg.png"]; photoalbumbg.anchorPoint = ccp(0,0); [self addChild:photoalbumbg z:0]; //Background Sound // [[SimpleAudioEngine sharedEngine]playBackgroundMusic:@"Background Music.wav" loop:YES]; CCSprite *photoalbumframe = [CCSprite spriteWithFile:@"photoalbumframe.png"]; photoalbumframe.position = ccp(160,240); [self addChild:photoalbumframe z:2]; CCSprite *frame = [CCSprite spriteWithFile:@"Photo-Frames.png"]; frame.position = ccp(160,270); [self addChild:frame z:1]; /*_____________________________________________________________________________________*/ CCMenuItemImage * upgradebtn = [CCMenuItemImage itemFromNormalImage:@"AlbumUpgrade.png" selectedImage:@"AlbumUpgrade.png" target:self selector:@selector(Upgrade:)]; CCMenu * fMenu = [CCMenu menuWithItems:upgradebtn,nil]; fMenu.position = ccp(200,110); [self addChild:fMenu z:3]; NSError *error; NSFileManager *fM = [NSFileManager defaultManager]; NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSLog(@"Documents directory: %@", [fM contentsOfDirectoryAtPath:documentsDirectory error:&error]); NSArray *allfiles = [fM contentsOfDirectoryAtPath :documentsDirectory error:&error]; directoryList = [[NSMutableArray alloc] init]; for(NSString *file in allfiles) { NSString *path = [documentsDirectory stringByAppendingPathComponent:file]; [directoryList addObject:file]; } NSLog(@"array file name value ==== %@", directoryList); CCSprite *temp = [CCSprite spriteWithFile:[directoryList objectAtIndex:0]]; [temp setTextureRect:CGRectMake(160.0f, 240.0f, 50,50)]; // temp.anchorPoint = ccp(0,0); [self addChild:temp z:10]; for(UIImage *file in directoryList) { // NSData *pngData = [NSData dataWithContentsOfFile:file]; // image = [UIImage imageWithData:pngData]; NSLog(@"uiimage = %@",image); // UIImage *image = [UIImage imageWithContentsOfFile:file]; for (int i=1; i<=3; i++) { for (int j=1;j<=3; j++) { CCTexture2D *tex = [[[CCTexture2D alloc] initWithImage:file] autorelease]; CCSprite *selectedimage = [CCSprite spriteWithTexture:tex rect:CGRectMake(0, 0, 67, 66)]; selectedimage.position = ccp(100*i,350*j); [self addChild:selectedimage]; } } } } return self; }

    Read the article

  • Encoded nsstring becomes invalid, "normal" nsstring remains

    - by shoreline
    I'm running into a problem with a string that contains encoded characters. Specifically, if the string has encoded characters it eventually becomes invalid while a "normal" string will not. in the .h file: @interface DirViewController : TTThumbsViewController <UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate> { NSString *sourceFolder; NSString *encodedSourceFolder; } @property (nonatomic, retain) NSString *sourceFolder; @property (nonatomic, retain) NSString *encodedSourceFolder; in the .m file: - (id)initWithFolder:(NSString*)folder query:(NSDictionary*)query { if (self = [super init]) { sourceFolder = folder; } return self; } Up to now everything seems to run as expected. In viewDidLoad I have the following: sourceFolderCopy = [self urlEncodeValue:(sourceFolder)]; //I also have this button, which I'll refer to later: UIBarButtonItem *importButton = [[UIBarButtonItem alloc] initWithTitle:@"Import/Export" style:UIBarButtonItemStyleBordered target:self action:@selector(importFiles:)]; self.navigationItem.rightBarButtonItem = importButton; Which uses the following method to encode the string (if it has characters I want encoded): - (NSString *)urlEncodeValue:(NSString *)str { NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes (kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8); return [result autorelease]; } If I NSLog result, I get the expected values. If the string has characters like a white space, I get a string with encoding. If the string doesn't have any characters that need to be encoded, it just gives me the original string. I have a button on the nav bar which begins an image import process by opening an action sheet. Once the method for the action sheet starts, my string is invalid - but only if it contains encoded characters. If it is just a "normal" string, everything is fine and acts as expected. Am I off on my encoding? At first I thought it might be a memory problem but I can't figure out why that would affect only encoded strings. Here's where the action sheet is defined (and the first place I can see the encoded string becoming invalid) the NSLog statements are where it crashes: - (IBAction)importFiles:(id)sender { NSLog(@"logging encodedSF from import files:"); NSLog(@"%@",encodedSourceFolder);//crashes right here NSLog(@"%@",sourceFolder); if (shouldNavigate == NO) { NSString *msg = nil; msg = @"It is not possible to import or export images while in image selection mode."; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unable to Import/Export" message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; [msg release]; } else{ UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"What would you like to do?" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Import Photos (Picker)", @"Export Photos", nil, nil]; [actionSheet showInView:self.view]; [actionSheet release]; } } I don't get any crash errors going to the console. By using breakpoints I was able to see that the encodedSourceFolder is invalid in the action sheet method.

    Read the article

  • Core Data - JSON (TouchJSON) on iPhone

    - by Urizen
    I have the following code which seems to go on indefinitely until the app crashes. It seems to happen with the recursion in the datastructureFromManagedObject method. I suspect that this method: 1) looks at the first managed object and follows any relationship property recursively. 2) examines the object at the other end of the relationship found at point 1 and repeats the process. Is it possible that if managed object A has a to-many relationship with object B and that relationship is two-way (i.e an inverse to-one relationship to A from B - e.g. one department has many employees but each employee has only one department) that the following code gets stuck in infinite recursion as it follows the to-one relationship from object B back to object A and so on. If so, can anyone provide a fix for this so that I can get my whole object graph of managed objects converted to JSON. #import "JSONUtils.h" @implementation JSONUtils - (NSDictionary*)dataStructureFromManagedObject:(NSManagedObject *)managedObject { NSDictionary *attributesByName = [[managedObject entity] attributesByName]; NSDictionary *relationshipsByName = [[managedObject entity] relationshipsByName]; //getting the values correspoinding to the attributes collected in attributesByName NSMutableDictionary *valuesDictionary = [[managedObject dictionaryWithValuesForKeys:[attributesByName allKeys]] mutableCopy]; //sets the name for the entity being encoded to JSON [valuesDictionary setObject:[[managedObject entity] name] forKey:@"ManagedObjectName"]; NSLog(@"+++++++++++++++++> before the for loop"); //looks at each relationship for the given managed object for (NSString *relationshipName in [relationshipsByName allKeys]) { NSLog(@"The relationship name = %@",relationshipName); NSRelationshipDescription *description = [relationshipsByName objectForKey:relationshipName]; if (![description isToMany]) { NSLog(@"The relationship is NOT TO MANY!"); [valuesDictionary setObject:[self dataStructureFromManagedObject:[managedObject valueForKey:relationshipName]] forKey:relationshipName]; continue; } NSSet *relationshipObjects = [managedObject valueForKey:relationshipName]; NSMutableArray *relationshipArray = [[NSMutableArray alloc] init]; for (NSManagedObject *relationshipObject in relationshipObjects) { [relationshipArray addObject:[self dataStructureFromManagedObject:relationshipObject]]; } [valuesDictionary setObject:relationshipArray forKey:relationshipName]; } return [valuesDictionary autorelease]; } - (NSArray*)dataStructuresFromManagedObjects:(NSArray*)managedObjects { NSMutableArray *dataArray = [[NSArray alloc] init]; for (NSManagedObject *managedObject in managedObjects) { [dataArray addObject:[self dataStructureFromManagedObject:managedObject]]; } return [dataArray autorelease]; } //method to call for obtaining JSON structure - i.e. public interface to this class - (NSString*)jsonStructureFromManagedObjects:(NSArray*)managedObjects { NSLog(@"-------------> just before running the recursive method"); NSArray *objectsArray = [self dataStructuresFromManagedObjects:managedObjects]; NSLog(@"-------------> just before running the serialiser"); NSString *jsonString = [[CJSONSerializer serializer] serializeArray:objectsArray]; return jsonString; } - (NSManagedObject*)managedObjectFromStructure:(NSDictionary*)structureDictionary withManagedObjectContext:(NSManagedObjectContext*)moc { NSString *objectName = [structureDictionary objectForKey:@"ManagedObjectName"]; NSManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:objectName inManagedObjectContext:moc]; [managedObject setValuesForKeysWithDictionary:structureDictionary]; for (NSString *relationshipName in [[[managedObject entity] relationshipsByName] allKeys]) { NSRelationshipDescription *description = [[[managedObject entity]relationshipsByName] objectForKey:relationshipName]; if (![description isToMany]) { NSDictionary *childStructureDictionary = [structureDictionary objectForKey:relationshipName]; NSManagedObject *childObject = [self managedObjectFromStructure:childStructureDictionary withManagedObjectContext:moc]; [managedObject setValue:childObject forKey:relationshipName]; continue; } NSMutableSet *relationshipSet = [managedObject mutableSetValueForKey:relationshipName]; NSArray *relationshipArray = [structureDictionary objectForKey:relationshipName]; for (NSDictionary *childStructureDictionary in relationshipArray) { NSManagedObject *childObject = [self managedObjectFromStructure:childStructureDictionary withManagedObjectContext:moc]; [relationshipSet addObject:childObject]; } } return managedObject; } //method to call for obtaining managed objects from JSON structure - i.e. public interface to this class - (NSArray*)managedObjectsFromJSONStructure:(NSString *)json withManagedObjectContext:(NSManagedObjectContext*)moc { NSError *error = nil; NSArray *structureArray = [[CJSONDeserializer deserializer] deserializeAsArray:[json dataUsingEncoding:NSUTF32BigEndianStringEncoding] error:&error]; NSAssert2(error == nil, @"Failed to deserialize\n%@\n%@", [error localizedDescription], json); NSMutableArray *objectArray = [[NSMutableArray alloc] init]; for (NSDictionary *structureDictionary in structureArray) { [objectArray addObject:[self managedObjectFromStructure:structureDictionary withManagedObjectContext:moc]]; } return [objectArray autorelease]; } @end

    Read the article

  • UIButtons in UIScrollView stop it scrolling, how to fix?

    - by Mark McFarlane
    Hi all, I have a problem with adding a set of UIButtons to a UIScrollView. With the buttons added it seems that the scroll command is not being passed to the scroll view as the buttons cover the whole surface. I've read various posts on this but still can't figure it out. I'm pretty new to iPhone programming so there's probably something obvious I've missed. I've tried things like canCancelContentTouches and delaysContentTouches to TRUE and FALSE. Here is the code I use to add the buttons to the scrollview. The scrollview was created in IB and is passed in to the function: -(void)drawCharacters:(NSMutableArray *)chars:(UIScrollView *)target_view { //NSLog(@"CLEARING PREVIOUS BUTTONS"); //clear previous buttons for parts/kanji if(target_view == viewParts){ for (UIButton *btn in parts_buttons) { [btn removeFromSuperview]; } [parts_buttons removeAllObjects]; } else if(target_view == viewKanji){ for (UIButton *btn in kanji_buttons) { [btn removeFromSuperview]; } [kanji_buttons removeAllObjects]; } //display options int chars_per_line = 9; //change this to change the number of chars displayed on each line if(target_view == viewKanji){ chars_per_line = 8; } int char_gap = 0; //change this to change the margin between chars int char_dimensions = (320/chars_per_line)-(char_gap*2); //set starting x, y coords int x = 0, y = 0; //increment y coord y += char_gap; //NSLog(@"ABOUT TO DRAW FIRST BUTTON"); for(NSMutableArray *char_arr in chars){ //increment x coord x += char_gap; //draw at x and y UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom]; myButton.frame = CGRectMake(x, y, char_dimensions, char_dimensions); // position in the parent view and set the size of the button [myButton setTitle:[char_arr objectAtIndex:0] forState:UIControlStateNormal]; [myButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal]; [myButton setTitleColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0] forState:UIControlStateDisabled]; myButton.titleLabel.font = [UIFont boldSystemFontOfSize:22]; if(target_view == viewKanji){ myButton.titleLabel.font = [UIFont boldSystemFontOfSize:30]; } // add targets and actions if(target_view == viewParts){ [myButton addTarget:self action:@selector(partSelected:) forControlEvents:UIControlEventTouchUpInside]; } else if(target_view == viewKanji){ [myButton addTarget:self action:@selector(kanjiSelected:) forControlEvents:UIControlEventTouchUpInside]; [myButton setTag:(int)[char_arr objectAtIndex:1]]; } //if the part isnt in the current list of kanji, disable and dim it if(target_view == viewParts){ if([kanji count] > 0){ [myButton setEnabled:NO]; } bool do_break = NO; for(NSMutableArray *arr in kanji){ //NSLog([NSString stringWithFormat:@"CHECKING PARTS AGAINST %d KANJI", [kanji count]]); for(NSString *str in [[arr objectAtIndex:2] componentsSeparatedByString:@" "]){ if(([myButton.titleLabel.text isEqualToString:str])){ //NSLog(@"--------------MATCH!!!-----------------"); [myButton setEnabled:YES]; for(NSString *str1 in parts_selected){ if(([myButton.titleLabel.text isEqualToString:str1])){ [myButton setEnabled:NO]; break; } } do_break = YES; break; } if(do_break) break; } if(do_break) break; } } // add to a view [target_view addSubview:myButton]; //update coords of next button x += char_dimensions+ char_gap; if (x > (320-char_dimensions)) { x = 0; y += char_dimensions + (char_gap*2); } //add button to global array to be removed from view next update if(target_view == viewParts){ [parts_buttons addObject:myButton]; } else if(target_view == viewKanji){ [kanji_buttons addObject:myButton]; } } //NSLog(@"FINISHED DRAWING ALL BUTTONS"); } Any help on this would be greatly appreciated. I just need to fix this to finish my app.

    Read the article

  • Getting Custom NSCell with NSButtonCell instance to handle mouse click/mouse events

    - by sidha
    OK I'm really stumped on this one. I want to make a checkbox with a NSTextFieldCell combined together. It's important that the checkbox goes ON if the mouse hits the box, NOT the text. I've accomplished this, more or less, but the issue is receiving the mouse event because I click one checkbox in a row, but ALL of them turn to NSOnState. I will show what I've done and my various failed attempts in order to get this to work. So this is how I've done it so far: header: @interface MyCheckboxCellToo : NSTextFieldCell { NSButtonCell *_checkboxCell; } implementation: - (NSUInteger)hitTestForEvent:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView { NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil]; NSLog(@"%@", NSStringFromPoint(point)); NSRect checkFrame; NSDivideRect(cellFrame, &checkFrame, &cellFrame, cellFrame.size.height/*3 + [[_checkboxCell image] size].width*/, NSMinXEdge); if (NSMouseInRect(point, checkFrame, [controlView isFlipped])) { // the checkbox, or the small region around it, was hit. so let's flip the state NSCellStateValue checkState = ([_checkboxCell state] == NSOnState) ? NSOffState:NSOnState; [self setState:checkState]; [_checkboxCell setState:checkState]; [controlView setNeedsDisplay:YES]; return NSCellHitTrackableArea; } return [super hitTestForEvent:event inRect:cellFrame ofView:controlView]; } I know I probably shouldn't be doing: [self setState:checkState]; [_checkboxCell setState:checkState]; [controlView setNeedsDisplay:YES]; in there... because the result is that EVERY checkbox in every goes to NSOnState. Is this because cells are re-used? How come the ImageAndTextCell can have different images in the same tableview? How do I handle the mouse event? I have tried: - (BOOL)trackMouse:(NSEvent *)theEvent inRect:(NSRect)cellFrame ofView:(NSView *)controlView untilMouseUp:(BOOL)untilMouseUp { NSLog(@"%s %@", _cmd, theEvent); return [_checkboxCell trackMouse:theEvent inRect:cellFrame ofView:controlView untilMouseUp:untilMouseUp]; // return YES; // return [super trackMouse:theEvent inRect:cellFrame ofView:controlView untilMouseUp:untilMouseUp]; } - (BOOL)startTrackingAt:(NSPoint)startPoint inView:(NSView *)controlView { NSLog(@"%s %@", _cmd, NSStringFromPoint(startPoint)); return [super startTrackingAt:startPoint inView:controlView]; } - (BOOL)continueTracking:(NSPoint)lastPoint at:(NSPoint)currentPoint inView:(NSView *)controlView { NSLog(@"%s %@", _cmd, NSStringFromPoint(currentPoint)); return [super continueTracking:lastPoint at:currentPoint inView:controlView]; } - (void)stopTracking:(NSPoint)lastPoint at:(NSPoint)stopPoint inView:(NSView *)controlView mouseIsUp:(BOOL)flag { NSLog(@"%s %d %@", _cmd, flag, NSStringFromPoint(stopPoint)); } trackMouse: ... DOES gets called but startTrackingAt:..., continueTracking:..., and stopTracking:.... DO NOT get called when I click on the checkbox "hit area" in trackMouse:... I have tried return [_checkboxCell trackMouse:theEvent inRect:cellFrame ofView:controlView untilMouseUp:untilMouseUp]; and return [super trackMouse:theEvent inRect:cellFrame ofView:controlView untilMouseUp:untilMouseUp]; and neither seems to result in the mouse event being handled by the checkbox. How do I get that single checkbox to go NSOnState? I know I'm pretty close but after a lot of doc reading and google searching I haven't been successful at solving this. suggestions and comments welcome.. OK here is a bit more to show creation and destruction of the object.. - (id)init { if ((self = [super init])) { _checkboxCell = [[NSButtonCell alloc] init]; [_checkboxCell setButtonType:NSSwitchButton]; [_checkboxCell setTitle:@""]; [_checkboxCell setTarget:self]; [_checkboxCell setImagePosition:NSImageLeft]; [_checkboxCell setControlSize:NSRegularControlSize]; } return self; } - copyWithZone:(NSZone *)zone { MyCheckboxCellToo *cell = (MyCheckboxCellToo *)[super copyWithZone:zone]; cell->_checkboxCell = [_checkboxCell copyWithZone:zone]; return cell; } - (void)dealloc { [_checkboxCell release]; [super dealloc]; }

    Read the article

  • Implementing ZBar QR Code Reader in UIView

    - by Bobster4300
    I really need help here. I'm pretty new to iOS/Objective-C so sorry if the problem resolution is obvious or if my code is terrible. Be easy on me!! :-) I'm struggling to integrate ZBarSDK for reading QR Codes into an iPad app i'm building. If I use ZBarReaderController (of which there are plenty of tutorials and guides on implementing), it works fine. However I want to make the camera come up in a UIView as opposed to the fullscreen camera. Now I have gotten as far as making the camera view (readerView) come up in the UIView (ZBarReaderView) as expected, but I get an error when it scans a code. The error does not come up until a code is scanned making me believe this is either delegate related or something else. Here's the important parts of my code: (ZBarSDK.h is imported at the PCH file) SignInViewController.h #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> @class AVCaptureSession, AVCaptureDevice; @interface SignInViewController : UIViewController < ZBarReaderDelegate > { ZBarReaderView *readerView; UITextView *resultText; } @property (nonatomic, retain) UIImagePickerController *imgPicker; @property (strong, nonatomic) IBOutlet UITextView *resultText; @property (strong, nonatomic) IBOutlet ZBarReaderView *readerView; -(IBAction)StartScan:(id) sender; SignInViewController.m #import "SignInViewController.h" @interface SignInViewController () @end @implementation SignInViewController @synthesize resultText, readerView; -(IBAction)StartScan:(id) sender { readerView = [ZBarReaderView new]; readerView.readerDelegate = self; readerView.tracksSymbols = NO; readerView.frame = CGRectMake(30,70,230,230); readerView.torchMode = 0; readerView.device = [self frontFacingCameraIfAvailable]; ZBarImageScanner *scanner = readerView.scanner; [scanner setSymbology: ZBAR_I25 config: ZBAR_CFG_ENABLE to: 0]; [self relocateReaderPopover:[self interfaceOrientation]]; [readerView start]; [self.view addSubview: readerView]; resultText.hidden=NO; } - (void) readerControllerDidFailToRead: (ZBarReaderController*) reader withRetry: (BOOL) retry{ NSLog(@"the image picker failing to read"); } - (void) imagePickerController: (UIImagePickerController*) reader didFinishPickingMediaWithInfo: (NSDictionary*) info { NSLog(@"the image picker is calling successfully %@",info); id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults]; ZBarSymbol *symbol = nil; NSString *hiddenData; for(symbol in results) hiddenData=[NSString stringWithString:symbol.data]; NSLog(@"the symbols is the following %@",symbol.data); resultText.text=symbol.data; NSLog(@"BARCODE= %@",symbol.data); NSLog(@"SYMBOL : %@",hiddenData); resultText.text=hiddenData; } The error I get when a code is scanned: 2012-12-16 14:28:32.797 QRTestApp[7970:907] -[SignInViewController readerView:didReadSymbols:fromImage:]: unrecognized selector sent to instance 0x1e88b1c0 2012-12-16 14:28:32.799 QRTestApp[7970:907] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SignInViewController readerView:didReadSymbols:fromImage:]: unrecognized selector sent to instance 0x1e88b1c0' I'm not too worried about what happens with the results just yet, just want to get over this error. Took me ages just to get the camera to come up in the UIView due to severe lack of tutorial or documentation on ZBarReaderView (for beginners anyway). Thanks all.

    Read the article

  • iphone app: delegate not responding

    - by Fiona
    Hi guys.. So i'm very new to this iphone development stuff.... and i'm stuck. I'm building an app that connects to the twitter api. However when the connectionDidFinishLoading method gets called, it doesn't seem to recognise the delegate. Here's the source code of the request class: import "OnePageRequest.h" @implementation OnePageRequest @synthesize username; @synthesize password; @synthesize receivedData; @synthesize delegate; @synthesize callback; @synthesize errorCallBack; @synthesize contactsArray; -(void)friends_timeline:(id)requestDelegate requestSelector:(SEL)requestSelector{ //set the delegate and selector self.delegate = requestDelegate; self.callback = requestSelector; //Set up the URL of the request to send to twitter!! NSURL *url = [NSURL URLWithString:@"http://twitter.com/statuses/friends_timeline.xml"]; [self request:url]; } -(void)request:(NSURL *) url{ theRequest = [[NSMutableURLRequest alloc] initWithURL:url]; theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConnection){ //Create the MSMutableData that will hold the received data. //receivedData is declared as a method instance elsewhere receivedData=[[NSMutableData data] retain]; }else{ //errorMessage.text = @"Error connecting to twitter!!"; } } -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ if ([challenge previousFailureCount] == 0){ NSLog(@"username: %@ ",[self username]); NSLog(@"password: %@ ",[self password]); NSURLCredential *newCredential = [NSURLCredential credentialWithUser:[self username] password:[self password] persistence:NSURLCredentialPersistenceNone]; [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; } else { [[challenge sender] cancelAuthenticationChallenge:challenge]; NSLog(@"Invalid Username or password!"); } } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ [receivedData setLength:0]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [receivedData appendData:data]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ [theConnection release]; [receivedData release]; [theRequest release]; NSLog(@"Connection failed. Error: %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSErrorFailingURLStringKey]); if(errorCallBack){ [delegate performSelector:errorCallBack withObject:error]; } } -(void)connectionDidFinishLoading:(NSURLConnection *)connection{ if (delegate && callback){ if([delegate respondsToSelector:[self callback]]){ [delegate performSelector:[self callback] withObject:receivedData]; }else{ NSLog(@"No response from delegate!"); } } [theConnection release]; [theRequest release]; [receivedData release]; } Here's the .h: @interface OnePageRequest : NSObject { NSString *username; NSString *password; NSMutableData *receivedData; NSURLRequest *theRequest; NSURLConnection *theConnection; id delegate; SEL callback; SEL errorCallBack; NSMutableArray *contactsArray; } @property (nonatomic,retain) NSString *username; @property (nonatomic,retain) NSString *password; @property (nonatomic,retain) NSMutableData *receivedData; @property (nonatomic,retain) id delegate; @property (nonatomic) SEL callback; @property (nonatomic) SEL errorCallBack; @property (nonatomic,retain) NSMutableArray *contactsArray; -(void)friends_timeline:(id)requestDelegate requestSelector:(SEL)requestSelector; -(void)request:(NSURL *) url; @end In the method: connectionDidFinishLoading, the following never gets executed: [delegate performSelector:[self callback] withObject:receivedData]; Instead I get the message: "No response from delegate" Anyone see what I'm doing wrong?! or what might be causing the problem? Regards, Fiona

    Read the article

  • I'm trying to pass a string from my first ViewController to my second ViewController but it returns NULL

    - by Dashony
    In my first view controller I have 3 input fields each of them take the user input into and saves it into a string such as: address, username and password as NSUserDefaults. This part works fine. In my second view controller I'm trying to take the 3 strings from first controller (address, username and password) create a html link based on the 3 strings. I've tried many ways to access the 3 strings with no luck, the result I get is NULL. Here is my code: //.h file - first view controller with the 3 input fields CamSetup.h #import <UIKit/UIKit.h> @interface CamSetup : UIViewController <UITextFieldDelegate> { NSString * address; NSString * username; NSString * password; IBOutlet UITextField * addressField; IBOutlet UITextField * usernameField; IBOutlet UITextField * passwordField; } -(IBAction) saveAddress: (id) sender; -(IBAction) saveUsername: (id) sender; -(IBAction) savePassword: (id) sender; @property(nonatomic, retain) UITextField *addressField; @property(nonatomic, retain) UITextField *usernameField; @property(nonatomic, retain) UITextField *passwordField; @property(nonatomic, retain) NSString *address; @property(nonatomic, retain) NSString *username; @property(nonatomic, retain) NSString *password; @end //.m file - first view controller CamSetup.m #import "CamSetup.h" @interface CamSetup () @end @implementation CamSetup @synthesize addressField, usernameField, passwordField, address, username, password; -(IBAction) saveAddress: (id) sender { address = [[NSString alloc] initWithFormat:addressField.text]; [addressField setText:address]; NSUserDefaults *stringDefaultAddress = [NSUserDefaults standardUserDefaults]; [stringDefaultAddress setObject:address forKey:@"stringKey1"]; NSLog(@"String [%@]", address); } -(IBAction) saveUsername: (id) sender { username = [[NSString alloc] initWithFormat:usernameField.text]; [usernameField setText:username]; NSUserDefaults *stringDefaultUsername = [NSUserDefaults standardUserDefaults]; [stringDefaultUsername setObject:username forKey:@"stringKey2"]; NSLog(@"String [%@]", username); } -(IBAction) savePassword: (id) sender { password = [[NSString alloc] initWithFormat:passwordField.text]; [passwordField setText:password]; NSUserDefaults *stringDefaultPassword = [NSUserDefaults standardUserDefaults]; [stringDefaultPassword setObject:password forKey:@"stringKey3"]; NSLog(@"String [%@]", password); } - (void)viewDidLoad { [addressField setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"stringKey1"]]; [usernameField setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"stringKey2"]]; [passwordField setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"stringKey3"]]; [super viewDidLoad]; } @end //.h second view controller LiveView.h #import <UIKit/UIKit.h> #import "CamSetup.h" @interface LiveView : UIViewController { NSString *theAddress; NSString *theUsername; NSString *thePassword; CamSetup *camsetup; //here is an instance of the first class } @property (nonatomic, retain) NSString *theAddress; @property (nonatomic, retain) NSString *theUsername; @property (nonatomic, retain) NSString *thePassword; @end //.m second view LiveView.m file #import "LiveView.h" @interface LiveView () @end @implementation LiveView @synthesize theAddress, theUsername, thePassword; - (void)viewDidLoad { [super viewDidLoad]; theUsername = camsetup.username; //this is probably not right? NSLog(@"String [%@]", theUsername); //resut here is NULL NSLog(@"String [%@]", camsetup.username); //and here NULL as well } @end

    Read the article

  • UITextView doesn't not resize when keyboard appear if loaded from a tab bar cotroller

    - by elio.d
    I have a simple view controller (SecondViewController) used to manage a UITextview (I'm building a simple editor) this is the code of the SecondViewController.h @interface SecondViewController : UIViewController { IBOutlet UITextView *textView; } @property (nonatomic,retain) IBOutlet UITextView *textView; @end and this is the SecondViewController.m // // EditorViewController.m // Editor // // Created by elio d'antoni on 13/01/11. // Copyright 2011 none. All rights reserved. // @implementation SecondViewController @synthesize textView; /* // Implement loadView to create a view hierarchy programmatically, without using a nib. - (void)loadView { } */ // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"uiViewBg.png"]]; textView.layer.borderWidth=1; textView.layer.cornerRadius=5; textView.layer.borderColor=[[UIColor darkGrayColor] CGColor]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil]; } -(void) matchAnimationTo:(NSDictionary *) userInfo { NSLog(@"match animation method"); [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]]; [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]]; } -(CGFloat) keyboardEndingFrameHeight:(NSDictionary *) userInfo { NSLog(@"keyboardEndingFrameHeight method"); CGRect keyboardEndingUncorrectedFrame = [[ userInfo objectForKey:UIKeyboardFrameEndUserInfoKey ] CGRectValue]; CGRect keyboardEndingFrame = [self.view convertRect:keyboardEndingUncorrectedFrame fromView:nil]; return keyboardEndingFrame.size.height; } -(CGRect) adjustFrameHeightBy:(CGFloat) change multipliedBy:(NSInteger) direction { NSLog(@"adjust method"); return CGRectMake(20, 57, self.textView.frame.size.width, self.textView.frame.size.height + change * direction); } -(void)keyboardWillAppear:(NSNotification *)notification { NSLog(@"keyboard appear"); [UIView beginAnimations:nil context:NULL]; [self matchAnimationTo:[notification userInfo]]; self.textView.frame = [self adjustFrameHeightBy:[self keyboardEndingFrameHeight: [notification userInfo]] multipliedBy:-1]; [UIView commitAnimations]; } -(void)keyboardWillDisappear:(NSNotification *) notification { NSLog(@"keyboard disappear"); [UIView beginAnimations:nil context:NULL]; [self matchAnimationTo:[notification userInfo]]; self.textView.frame = [self adjustFrameHeightBy:[self keyboardEndingFrameHeight: [notification userInfo]] multipliedBy:1]; [UIView commitAnimations]; } // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return YES; } (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } (void)dealloc { [super dealloc]; } @end the problem is that if load the view controller from a tab bar controller the textView doesn't resize when the keyboard appear, but the SAME code works if loaded as a single view based app. I hope I was clear enough. I used the tabBar template provided by xcode no modifications.

    Read the article

  • NSMutableArray memory leak when reloading objects

    - by Davin
    I am using Three20/TTThumbsviewcontroller to load photos. I am struggling since quite a some time now to fix memory leak in setting photosource. I am beginner in Object C & iOS memory management. Please have a look at following code and suggest any obvious mistakes or any errors in declaring and releasing variables. -- PhotoViewController.h @interface PhotoViewController : TTThumbsViewController <UIPopoverControllerDelegate,CategoryPickerDelegate,FilterPickerDelegate,UISearchBarDelegate>{ ...... NSMutableArray *_photoList; ...... @property(nonatomic,retain) NSMutableArray *photoList; -- PhotoViewController.m @implementation PhotoViewController .... @synthesize photoList; ..... - (void)LoadPhotoSource:(NSString *)query:(NSString *)title:(NSString* )stoneName{ NSLog(@"log- in loadPhotosource method"); if (photoList == nil) photoList = [[NSMutableArray alloc] init ]; [photoList removeAllObjects]; @try { sqlite3 *db; NSFileManager *fileMgr = [NSFileManager defaultManager]; NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *dbPath = [documentsPath stringByAppendingPathComponent: @"DB.s3db"]; BOOL success = [fileMgr fileExistsAtPath:dbPath]; if(!success) { NSLog(@"Cannot locate database file '%@'.", dbPath); } if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)) { NSLog(@"An error has occured."); } NSString *_sql = query;//[NSString stringWithFormat:@"SELECT * FROM Products where CategoryId = %i",[categoryId integerValue]]; const char *sql = [_sql UTF8String]; sqlite3_stmt *sqlStatement; if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK) { NSLog(@"Problem with prepare statement"); } if ([stoneName length] != 0) { NSString *wildcardSearch = [NSString stringWithFormat:@"%@%%",[stoneName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]; sqlite3_bind_text(sqlStatement, 1, [wildcardSearch UTF8String], -1, SQLITE_STATIC); } while (sqlite3_step(sqlStatement)==SQLITE_ROW) { NSString* urlSmallImage = @"Mahallati_NoImage.png"; NSString* urlThumbImage = @"Mahallati_NoImage.png"; NSString *designNo = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)]; designNo = [designNo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSString *desc = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,7)]; desc = [desc stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSString *caption = designNo;//[designNo stringByAppendingString:desc]; caption = [caption stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSString *smallFilePath = [documentsPath stringByAppendingPathComponent: [NSString stringWithFormat:@"Small%@.JPG",designNo] ]; smallFilePath = [smallFilePath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; if ([fileMgr fileExistsAtPath:smallFilePath]){ urlSmallImage = [NSString stringWithFormat:@"Small%@.JPG",designNo]; } NSString *thumbFilePath = [documentsPath stringByAppendingPathComponent: [NSString stringWithFormat:@"Thumb%@.JPG",designNo] ]; thumbFilePath = [thumbFilePath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; if ([fileMgr fileExistsAtPath:thumbFilePath]){ urlThumbImage = [NSString stringWithFormat:@"Thumb%@.JPG",designNo]; } NSNumber *photoProductId = [NSNumber numberWithInt:(int)sqlite3_column_int(sqlStatement, 0)]; NSNumber *photoPrice = [NSNumber numberWithInt:(int)sqlite3_column_int(sqlStatement, 6)]; char *productNo1 = sqlite3_column_text(sqlStatement, 3); NSString* productNo; if (productNo1 == NULL) productNo = nil; else productNo = [NSString stringWithUTF8String:productNo1]; Photo *jphoto = [[[Photo alloc] initWithCaption:caption urlLarge:[NSString stringWithFormat:@"documents://%@",urlSmallImage] urlSmall:[NSString stringWithFormat:@"documents://%@",urlSmallImage] urlThumb:[NSString stringWithFormat:@"documents://%@",urlThumbImage] size:CGSizeMake(123, 123) productId:photoProductId price:photoPrice description:desc designNo:designNo productNo:productNo ] autorelease]; [photoList addObject:jphoto]; [jphoto release]; } } @catch (NSException *exception) { NSLog(@"An exception occured: %@", [exception reason]); } self.photoSource = [[[MockPhotoSource alloc] initWithType:MockPhotoSourceNormal title:[NSString stringWithFormat: @"%@",title] photos: photoList photos2:nil] autorelease]; } Memory leaks happen when calling above LoadPhotosource method again with different query... I feel its something wrong in declaring NSMutableArray (photoList), but can't figure out how to fix memory leak. Any suggestion is really appreciated.

    Read the article

  • Build a Drill Down TableView with arrays

    - by skiria
    I'm trying to build a Drill down tableview to show the information that I have in a hierachy of arrays and classes. I have 3 classes: class Video { nameVideo, id, description, user... } class Topic {nameTopic, topicID, NSMutableArray videos; } class Category {nameCategory, categoryID, NSMUtableArray topics} And then in my app delegate I defined //AppDelegate.h NSMutableArray categories; The app display the tableView with nameCategory, but then, when I select a row it shows a tableview with 0 rows. If I check, for the second view the NumberOfRowsInSection, it returns me 0. I supose that the error is that I don't build correctly the provisional array called tableDataSource, I don't know the reason why it doesn't copy the new information on this array. ` - (void)viewDidLoad { [super viewDidLoad]; appDelegate = (TSCAppDelegate *)[[UIApplication sharedApplication] delegate]; //self.title = @"Categoria"; if(CurrentLevel == 0) { //Initialize our table data source NSArray *tempArray = [[NSArray alloc] init]; self.tableDataSource = tempArray; [tempArray release]; self.tableDataSource = appDelegate.categories; self.navigationItem.title = @"Categoria"; CurrentTitle = @"Categoria"; } else { self.navigationItem.title = CurrentTitle; } } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSLog (@"contador_ %i,", [self.tableDataSource count]); //--> On the second view it is 0! return [self.tableDataSource count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]autorelease]; } // Configure the cell. if (CurrentLevel == 0) { Category *aCategory = [self.tableDataSource objectAtIndex:indexPath.row]; cell.text = aCategory.nameCategory; } if (CurrentLevel == 1) { Topic *aTopic = [self.tableDataSource objectAtIndex:indexPath.row]; cell.text = aTopic.nameTopic; } else if ([CurrentLevel == 0]){ Topic *aTopic = [self.tableDataSource objectAtIndex:indexPath.row]; cell.text = aTopic.nameTopic; //NSLog(@"inside!!"); } cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //Get the actual Category Category *aCategory = [self.tableDataSource objectAtIndex:indexPath.row]; //NSLog (@" CATEGORY: %@", aCategory.nameCategory); //NSLog (@" CATEGORY: %i", aCategory.categoryID); //NSLog (@" TOPICS OF CATEGORY: %i", [aCategory.topics count]); //Prepare to tableview. navegaTableViewController *nvController = [[navegaTableViewController alloc] initWithNibName:@"navegaTableView" bundle:[NSBundle mainBundle]]; //Increment the Current View nvController.CurrentLevel += 1; //Set the title; nvController.CurrentTitle = @"Topic"; nvController.tableDataSource = aCategory.topics; //Push the new table view on the stack [self.navigationController pushViewController:nvController animated:YES]; [nvController release]; } `

    Read the article

  • Synchronous communication using NSOperationQueue

    - by chip_munks
    I am new to Objective C programming. I have created two threads called add and display using the NSInvocationOperation and added it on to the NSOperationQueue. I make the display thread to run first and then run the add thread. The display thread after printing the "Welcome to display" has to wait for the results to print from the add method. So i have set the waitUntilFinished method. Both the Operations are on the same queue. If i use waitUntilFinished for operations on the same queue there may be a situation for deadlock to happen(from apples developer documentation). Is it so? To wait for particular time interval there is a method called waitUntilDate: But if i need to like this wait(min(100,dmax)); let dmax = 20; How to do i wait for these conditions? It would be much helpful if anyone can explain with an example. EDITED: threadss.h ------------ #import <Foundation/Foundation.h> @interface threadss : NSObject { BOOL m_bRunThread; int a,b,c; NSOperationQueue* queue; NSInvocationOperation* operation; NSInvocationOperation* operation1; NSConditionLock* theConditionLock; } -(void)Thread; -(void)add; -(void)display; @end threadss.m ------------ #import "threadss.h" @implementation threadss -(id)init { if (self = [super init]) { queue = [[NSOperationQueue alloc]init]; operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(display) object:nil]; operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(add) object:nil]; theConditionLock = [[NSConditionLock alloc]init]; } return self; } -(void)Thread { m_bRunThread = YES; //[operation addDependency:operation1]; if (m_bRunThread) { [queue addOperation:operation]; } //[operation addDependency:operation1]; [queue addOperation:operation1]; //[self performSelectorOnMainThread:@selector(display) withObject:nil waitUntilDone:YES]; //NSLog(@"I'm going to do the asynchronous communication btwn the threads!!"); //[self add]; //[operation addDependency:self]; sleep(1); [queue release]; [operation release]; //[operation1 release]; } -(void)add { NSLog(@"Going to add a and b!!"); a=1; b=2; c = a + b; NSLog(@"Finished adding!!"); } -(void)display { NSLog(@"Into the display method"); [operation1 waitUntilFinished]; NSLog(@"The Result is:%d",c); } @end main.m ------- #import <Foundation/Foundation.h> #import "threadss.h" int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; threadss* thread = [[threadss alloc]init]; [thread Thread]; [pool drain]; return 0; } This is what i have tried with a sample program. output 2011-06-03 19:40:47.898 threads_NSOperationQueue[3812:1503] Going to add a and b!! 2011-06-03 19:40:47.898 threads_NSOperationQueue[3812:1303] Into the display method 2011-06-03 19:40:47.902 threads_NSOperationQueue[3812:1503] Finished adding!! 2011-06-03 19:40:47.904 threads_NSOperationQueue[3812:1303] The Result is:3 Is the way of invoking the thread is correct. 1.Will there be any deadlock condition? 2.How to do wait(min(100,dmax)) where dmax = 50.

    Read the article

  • iPhone MapKit problems: viewForAnnotation inconsistently setting pinColor?

    - by blackkettle
    Hi, I'm trying setup a map that displays different pin colors depending on the type/class of the location in question. I know this is a pretty common thing to do, but I'm having trouble getting the viewForAnnotation delegate to consistently update/set the pin color. I have a showThisLocation function that basically cycles through a list of AddressAnnotations and then based on the annotation class (bus stop, hospital, etc.) I set an if( myClass == 1){ [defaults setObject:@"1" forKey:@"currPinColor"]; [defaults synchronize]; NSLog(@"Should be %@!", [defaults objectForKey:@"currPinColor"]); } else if( myClass ==2 ){ [defaults setObject:@"2" forKey:@"currPinColor"]; [defaults synchronize]; NSLog(@"Should be %@!", [defaults objectForKey:@"currPinColor"]); } [_mapView addAnnotation:myCurrentAnnotation]; then my viewForAnnotation delegate looks like this, - (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation { if( annotation == mapView.userLocation ){ return nil; } NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; MKPinAnnotationView *annView = nil; annView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"currentloc"]; if( annView == nil ){ annView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"]; } annView.pinColor = [defaults integerForKey:@"currPinColor"]; NSLog(@"Pin color: %d", [defaults integerForKey:@"currPinColor"]); annView.animatesDrop=TRUE; annView.canShowCallout = YES; annView.calloutOffset = CGPointMake(-5, 5); return annView; } The problem is that, although the NSLog statements in the "if" block always confirm that the color has been set, the delegate sometimes but not always ends up with the correct color. I've also noticed that what generally happens is that the first search for a new location will set all pins to the last color in the "if" block, but search for the same location again will set the pins to the correct color. I suspect I am not supposed to usen NSUserDefaults in this way, but I also tried to create my own subclass for MKAnnotation which included an additional property "currentPinColor", and while this allowed me to set the "currentPinColor", when I tried to access the "currentPinColor from the delegate method, the compiler complained that it didn't know anything about "currentPinColor in connection with MKAnnotation. Fair enough I guess, but then I tried to revise the delegate method, - (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation instead of the default - (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation at which point the compiler complained that it didn't know anything about the protocol for MyCustomMKAnnotation in this delegate context. What is the proper way to set the delegate method and/or MyCustomMKAnnotation, or what is the appropriate way to achieve consistent pinColor settings. I'm just about out of ideas for things to try here.

    Read the article

  • UIScrollView imageViewDidEndZooming not being called

    - by Jorge
    I have this subclass of UIScrollView: @interface MyScrollView : UIScrollView <UIScrollViewDelegate> And I have those delegate methods - (void)scrollViewDidEndZooming:(UIScrollView *)aScrollView withView:(UIView *)view atScale(float)aScale{ NSLog(@"zoomed"); } - (UIView *)viewForZoomingInScrollView:(UIScrollView *)aScrollView{ NSLog(@"willzoom"); } When I zoom in MyScrollView viewForZoomingInScrollView is called but scrollViewDidEndZooming never gets called. Any idea why??

    Read the article

  • Records not being saved to core data sqlite file

    - by esd100
    I'm a complete newbie when it comes to iOS programming and much less Core Data. It's rather non-intuitive for me, as I really came into my own with programming with MATLAB, which I guess is more of a 'scripting' language. At any rate, my problem is that I had no idea what I had to do to create a database for my application. So I read a little bit and thought I had to create a SQL database of my stuff and then import it. Long story short, I created a SQLite db and I want to use the work I have already done to import stuff into my CoreData database. I tried exporting to comma-delimited files and xml files and reading those in, but I didn't like it and it seemed like an extra step that I shouldn't need to do. So, I imported the SQLite database into my resources and added the sqlite framework. I have my core data model setup and it is setting up the SQLite database for the model correctly in the background. When I run through my program to add objects to my entities, it seems to work and I can even fetch results afterward. However, when I inspect the Core Data Database SQLite file, no records have been saved. How is it possible for it to fetch results but not save them to the database? - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ //load in the path for resources NSString *paths = [[NSBundle mainBundle] resourcePath]; NSString *databaseName = @"histology.sqlite"; NSString *databasePath = [paths stringByAppendingPathComponent:databaseName]; [self createDatabase:databasePath ]; NSError *error; if ([[self managedObjectContext] save:&error]) { NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]); } // Test listing all CELLS from the store NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entityMO = [NSEntityDescription entityForName:@"CELL" inManagedObjectContext:[self managedObjectContext]]; [fetchRequest setEntity:entityMO]; NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error]; for (CELL *cellName in fetchedObjects) { //NSLog(@"cellName: %@", cellName); } -(void) createDatabase:databasePath { NSLog(@"The createDatabase function was entered."); NSLog(@"The databasePath is %@ ",[databasePath description]); // Setup the database object sqlite3 *histoDatabase; // Open the database from filessytem if(sqlite3_open([databasePath UTF8String], &histoDatabase) == SQLITE_OK) { NSLog(@"The database was opened"); // Setup the SQL Statement and compile it for faster access const char *sqlStatement = "SELECT * FROM CELL"; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(histoDatabase, sqlStatement, -1, &compiledStatement, NULL) != SQLITE_OK) { NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(histoDatabase)); } if(sqlite3_prepare_v2(histoDatabase, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { // Loop through the results and add them to cell MO array while(sqlite3_step(compiledStatement) == SQLITE_ROW) { CELL *cellMO = [NSEntityDescription insertNewObjectForEntityForName:@"CELL" inManagedObjectContext:[self managedObjectContext]]; if (sqlite3_column_type(compiledStatement, 0) != SQLITE_NULL) { cellMO.cellName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)]; } else { cellMO.cellName = @"undefined"; } if (sqlite3_column_type(compiledStatement, 1) != SQLITE_NULL) { cellMO.cellDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]; } else { cellMO.cellDescription = @"undefined"; } NSLog(@"The contents of NSString *cellName = %@",[cellMO.cellName description]); } } // Release the compiled statement from memory sqlite3_finalize(compiledStatement); } sqlite3_close(histoDatabase); } I have a feeling that it has something to do with the timing of opening/closing both of the databases? Attached I have some SQL debugging output to the terminal 2012-05-28 16:03:39.556 MedPix[34751:fb03] The createDatabase function was entered. 2012-05-28 16:03:39.557 MedPix[34751:fb03] The databasePath is /Users/jack/Library/Application Support/iPhone Simulator/5.1/Applications/A6B2A79D-BA93-4E24-9291-5B7948A3CDF4/MedPix.app/histology.sqlite 2012-05-28 16:03:39.559 MedPix[34751:fb03] The database was opened 2012-05-28 16:03:39.560 MedPix[34751:fb03] The database was prepared 2012-05-28 16:03:39.575 MedPix[34751:fb03] CoreData: annotation: Connecting to sqlite database file at "/Users/jack/Library/Application Support/iPhone Simulator/5.1/Applications/A6B2A79D-BA93-4E24-9291-5B7948A3CDF4/Documents/MedPix.sqlite" 2012-05-28 16:03:39.576 MedPix[34751:fb03] CoreData: annotation: creating schema. 2012-05-28 16:03:39.577 MedPix[34751:fb03] CoreData: sql: pragma page_size=4096 2012-05-28 16:03:39.578 MedPix[34751:fb03] CoreData: sql: pragma auto_vacuum=2 2012-05-28 16:03:39.630 MedPix[34751:fb03] CoreData: sql: BEGIN EXCLUSIVE 2012-05-28 16:03:39.631 MedPix[34751:fb03] CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_METADATA' 2012-05-28 16:03:39.632 MedPix[34751:fb03] CoreData: sql: CREATE TABLE ZCELL ( Z_PK INTEGER PRIMARY KEY, Z_ENT INTEGER, Z_OPT INTEGER, ZCELLDESCRIPTION VARCHAR, ZCELLNAME VARCHAR ) ... 2012-05-28 16:03:39.669 MedPix[34751:fb03] CoreData: annotation: Creating primary key table. 2012-05-28 16:03:39.671 MedPix[34751:fb03] CoreData: sql: CREATE TABLE Z_PRIMARYKEY (Z_ENT INTEGER PRIMARY KEY, Z_NAME VARCHAR, Z_SUPER INTEGER, Z_MAX INTEGER) 2012-05-28 16:03:39.672 MedPix[34751:fb03] CoreData: sql: INSERT INTO Z_PRIMARYKEY(Z_ENT, Z_NAME, Z_SUPER, Z_MAX) VALUES(1, 'CELL', 0, 0) ... 2012-05-28 16:03:39.701 MedPix[34751:fb03] CoreData: sql: CREATE TABLE Z_METADATA (Z_VERSION INTEGER PRIMARY KEY, Z_UUID VARCHAR(255), Z_PLIST BLOB) 2012-05-28 16:03:39.702 MedPix[34751:fb03] CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_METADATA' 2012-05-28 16:03:39.703 MedPix[34751:fb03] CoreData: sql: DELETE FROM Z_METADATA WHERE Z_VERSION = ? 2012-05-28 16:03:39.704 MedPix[34751:fb03] CoreData: sql: INSERT INTO Z_METADATA (Z_VERSION, Z_UUID, Z_PLIST) VALUES (?, ?, ?) 2012-05-28 16:03:39.705 MedPix[34751:fb03] CoreData: sql: COMMIT 2012-05-28 16:03:39.710 MedPix[34751:fb03] CoreData: sql: pragma cache_size=200 2012-05-28 16:03:39.711 MedPix[34751:fb03] CoreData: sql: SELECT Z_VERSION, Z_UUID, Z_PLIST FROM Z_METADATA 2012-05-28 16:03:39.712 MedPix[34751:fb03] The contents of NSString *cellName = Beta Cell 2012-05-28 16:03:39.712 MedPix[34751:fb03] The contents of NSString *cellName = Gastric Chief Cell ... 2012-05-28 16:03:39.714 MedPix[34751:fb03] The database was prepared 2012-05-28 16:03:39.764 MedPix[34751:fb03] The createDatabase function has finished. Now fetching. 2012-05-28 16:03:39.765 MedPix[34751:fb03] CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZCELLDESCRIPTION, t0.ZCELLNAME FROM ZCELL t0 2012-05-28 16:03:39.766 MedPix[34751:fb03] CoreData: annotation: sql connection fetch time: 0.0008s 2012-05-28 16:03:39.767 MedPix[34751:fb03] CoreData: annotation: total fetch execution time: 0.0016s for 0 rows. 2012-05-28 16:03:39.768 MedPix[34751:fb03] cellName: <CELL: 0x6bbc120> (entity: CELL; id: 0x6bbc160 <x-coredata:///CELL/t57D10DDD-74E2-474F-97EE-E3BD0FF684DA34> ; data: { cellDescription = "S cells are cells which release secretin, found in the jejunum and duodenum. They are stimulated by a drop in pH to 4 or below in the small intestine's lumen. The released secretin will increase the s"; cellName = "S Cell"; organs = ( ); specimens = ( ); systems = ( ); tissues = ( ); }) ... Sections were cut short to abbreviate. But note that the fetch results contain information, but it says that total fetch execution was for "0" rows? How can that be? Any help will be greatly appreciated, especially detailed explanations. :) Thanks.

    Read the article

  • Cocoa: AVAudioRecorder Fails to Record

    - by kumaryr
    AVAudioSession *audioSession = [AVAudioSession sharedInstance]; NSError *err = nil; [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&err]; if(err){ NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); return; } [audioSession setActive:YES error:&err]; err = nil; if(err){ NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); return; } NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init]; [recordSetting setValue:[NSNumber numberWithInt: kAudioFormatAppleIMA4] forKey:AVFormatIDKey]; [recordSetting setValue:[NSNumber numberWithFloat:40000.0] forKey:AVSampleRateKey]; [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey]; [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; [recordSetting setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey]; [recordSetting setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey]; // Create a new dated file NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0]; NSString *caldate = [now description]; NSString *recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain]; NSLog(recorderFilePath); url = [NSURL fileURLWithPath:recorderFilePath]; err = nil; recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err]; if(!recorder){ NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]); UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Warning" message: [err localizedDescription] delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; return; } //prepare to record [recorder setDelegate:self]; [recorder prepareToRecord]; recorder.meteringEnabled = YES; BOOL audioHWAvailable = audioSession.inputIsAvailable; if (! audioHWAvailable) { UIAlertView *cantRecordAlert = [[UIAlertView alloc] initWithTitle: @"Warning" message: @"Audio input hardware not available" delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [cantRecordAlert show]; [cantRecordAlert release]; return; } // [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector( updateTimerDisplay) userInfo:nil repeats:YES]; // [recorder recordForDuration:(NSTimeInterval)10 ]; // [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector( updateTimerDisplay) userInfo:nil repeats:YES];

    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

  • how to update database table in sqlite3 iphone

    - by Ajeet Kumar Yadav
    Hi I am new in Iphone i am developing application that is use database but i am face problem. In My application I am using table view. I am fetch the value from database in the table view this is done after that we also insert value throw text field in that table of database and display that value in table view.I am also use another table in database table name is Alootikki the value of table alootikki is display in other table view in application and user want to add this table alootikki value in first table of database and display that value in table view when we do this value is display only in the table view this is not write in the database table. when value is display and user want to add other data throw text field then only that add value is show first value is remove from table view. I am not able to solve this plz help me. The code is given bellow for database -(void)Data1 { //////databaseName = @"dataa.sqlite"; databaseName = @"Recipe1.sqlite"; NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath =[documentsDir stringByAppendingPathComponent:databaseName]; [self checkAndCreateDatabase]; list1 = [[NSMutableArray alloc] init]; sqlite3 *database; if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { if(addStmt == nil) { ////////////const char *sql = "insert into Dataa(item) Values(?)"; const char *sql = " insert into Slist(Incredients ) Values(?)"; if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK) NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database)); } sqlite3_bind_text(addStmt, 1, [i UTF8String], -1, SQLITE_TRANSIENT); //sqlite3_bind_int(addStmt,1,i); // sqlite3_bind_text(addStmt, 1, [coffeeName UTF8String], -1, SQLITE_TRANSIENT); // sqlite3_bind_double(addStmt, 2, [price doubleValue]); if(SQLITE_DONE != sqlite3_step(addStmt)) NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database)); else //SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid coffeeID = sqlite3_last_insert_rowid(database); //Reset the add statement. sqlite3_reset(addStmt); // sqlite3_clear_bindings(detailStmt); //} } sqlite3_finalize(addStmt); addStmt = nil; sqlite3_close(database); } -(void)sopinglist { databaseName= @"Recipe1.sqlite"; NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath =[documentsDir stringByAppendingPathComponent:databaseName]; [self checkAndCreateDatabase]; list1 = [[NSMutableArray alloc] init]; sqlite3 *database; if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { if(addStmt == nil) { ///////////const char *sql = "insert into Dataa(item) Values(?)"; const char *sql = " insert into Slist(Incredients,Recipename,foodtype ) Values(?,?,?)"; ///////////// const char *sql =" Update Slist ( Incredients, Recipename,foodtype) Values(?,?,?)"; if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK) NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database)); } /////for( NSString * j in k) sqlite3_bind_text(addStmt, 1, [k UTF8String], -1, SQLITE_TRANSIENT); //sqlite3_bind_int(addStmt,1,i); // sqlite3_bind_text(addStmt, 1, [coffeeName UTF8String], -1, SQLITE_TRANSIENT); // sqlite3_bind_double(addStmt, 2, [price doubleValue]); if(SQLITE_DONE != sqlite3_step(addStmt)) NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database)); else //SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid coffeeID = sqlite3_last_insert_rowid(database); //Reset the add statement. sqlite3_reset(addStmt); // sqlite3_clear_bindings(detailStmt); //} } sqlite3_finalize(addStmt); addStmt = nil; sqlite3_close(database); } -(void)Data { ////////////////databaseName = @"dataa.sqlite"; databaseName = @"Recipe1.sqlite"; NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath =[documentsDir stringByAppendingPathComponent:databaseName]; [self checkAndCreateDatabase]; list1 = [[NSMutableArray alloc] init]; sqlite3 *database; if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { if(detailStmt == nil) { const char *sql = "Select * from Slist "; if(sqlite3_prepare_v2(database, sql, -1, &detailStmt, NULL) == SQLITE_OK) { //NSLog(@"Hiiiiiii"); //sqlite3_bind_text(detailStmt, 1, [t1 UTF8String], -1, SQLITE_TRANSIENT); //sqlite3_bind_text(detailStmt, 2, [t2 UTF8String], -2, SQLITE_TRANSIENT); //sqlite3_bind_int(detailStmt, 3, t3); while(sqlite3_step(detailStmt) == SQLITE_ROW) { NSLog(@"Helllloooooo"); //NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)]; NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)]; char *str=( char*)sqlite3_column_text(detailStmt, 0); if( str) { item = [ NSString stringWithUTF8String:str ]; } else { item= @""; } //+ (NSString*)stringWithCharsIfNotNull: (char*)item /// { // if ( item == NULL ) // return nil; //else // return [[NSString stringWithUTF8String: item] //stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; //} //NSString *fame= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 1)]; //NSString *cinemax = [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 2)]; //NSString *big= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 3)]; //pvr1 = pvr; item1=item; //NSLog(@"%@",item1); data = [[NSMutableArray alloc] init]; list *animal=[[list alloc] initWithName:item1]; // Add the animal object to the animals Array [list1 addObject:animal]; //[list1 addObject:item]; } sqlite3_reset(detailStmt); } sqlite3_finalize(detailStmt); // sqlite3_clear_bindings(detailStmt); } } detailStmt = nil; sqlite3_close(database); } (void)recpies { /////////////////////databaseName = @"Data.sqlite"; databaseName = @"Recipe1.sqlite"; NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath =[documentsDir stringByAppendingPathComponent:databaseName]; [self checkAndCreateDatabase]; list1 = [[NSMutableArray alloc] init]; sqlite3 *database; if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { if(detailStmt == nil) { //////const char *sql = "Select * from Dataa"; const char *sql ="select *from alootikki"; if(sqlite3_prepare_v2(database, sql, -1, &detailStmt, NULL) == SQLITE_OK) { //NSLog(@"Hiiiiiii"); //sqlite3_bind_text(detailStmt, 1, [t1 UTF8String], -1, SQLITE_TRANSIENT); //sqlite3_bind_text(detailStmt, 2, [t2 UTF8String], -2, SQLITE_TRANSIENT); //sqlite3_bind_int(detailStmt, 3, t3); while(sqlite3_step(detailStmt) == SQLITE_ROW) { //NSLog(@"Helllloooooo"); //NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)]; NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)]; char *str=( char*)sqlite3_column_text(detailStmt, 0); if( str) { item = [ NSString stringWithUTF8String:str ]; } else { item= @""; } //NSString *fame= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 1)]; //NSString *cinemax = [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 2)]; //NSString *big= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 3)]; //pvr1 = pvr; item1=item; //NSLog(@"%@",item1); data = [[NSMutableArray alloc] init]; list *animal=[[list alloc] initWithName:item1]; // Add the animal object to the animals Array [list1 addObject:animal]; //[list1 addObject:item]; } sqlite3_reset(detailStmt); } sqlite3_finalize(detailStmt); // sqlite3_clear_bindings(detailStmt); } } detailStmt = nil; sqlite3_close(database); }

    Read the article

  • Unix System Call in Objective-C

    - by Biranchi
    Hi all, Is it possible to make system call in Objective-C? I have the following code: if (!system("ls -l")) { NSLog(@"Successfully executed"); } else { NSLog(@"Error while executing the command"); } How to get the output? Thanks

    Read the article

  • SnowLeopard Xcode warning: "format not a string literal and no format arguments"

    - by Justin Galzic
    Since upgrading to the latest XCode 3.2.1 and SnowLeopard, I've been getting the warning, "format not a string literal and no format arguments" on the following: NSError *error = nil; if (![self.managedObjectContext save:&error]) { NSLog([NSString stringWithFormat:@"%@ %@, %@", errorMsgFormat, error, [error userInfo]]); } If 'errorMsgFormat' is an NSString with format specifiers (eg: "print me like this: %@"), what is wrong with the above NSLog statement? And what is the recommended way to fix it so that the warning isn't generated?

    Read the article

  • AVAudioPlayer crash after playing from an AVAudioRecorder

    - by munchine
    I've got a button the user tap to start recording and tap again to stop. When it stop I want the recorded voice 'echo' back so the user can hear what was recorded. This works fine the first time. If I hit the button for the third time, it starts a new recording and when I hit stop it crashes with EXC_BAD_ACCESS. - (IBAction) readToMeTapped { if(recording) { recording = NO; [readToMeButton setTitle:@"Stop Recording" forState: UIControlStateNormal ]; NSMutableDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithFloat: 44100.0], AVSampleRateKey, [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey, [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, [NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey, nil]; // Create a new dated file NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0]; NSString *caldate = [now description]; recordedTmpFile = [NSURL fileURLWithPath:[[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain]]; error = nil; recorder = [[ AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSetting error:&error]; [recordSetting release]; if(!recorder){ NSLog(@"recorder: %@ %d %@", [error domain], [error code], [[error userInfo] description]); UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Warning" message: [error localizedDescription] delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; return; } NSLog(@"Using File called: %@",recordedTmpFile); //Setup the recorder to use this file and record to it. [recorder setDelegate:self]; [recorder prepareToRecord]; [recorder recordForDuration:(NSTimeInterval) 5]; //recording for a limited time } else { // it crashes the second time it gets here! recording = YES; NSLog(@"Recording YES Using File called: %@",recordedTmpFile); [readToMeButton setTitle:@"Start Recording" forState:UIControlStateNormal ]; [recorder stop]; //Stop the recorder. //playback recording AVAudioPlayer * newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&error]; [recordedTmpFile release]; self.aPlayer = newPlayer; [newPlayer release]; [aPlayer setDelegate:self]; [aPlayer prepareToPlay]; [aPlayer play]; } } - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)sender successfully:(BOOL)flag { NSLog (@"audioRecorderDidFinishRecording:successfully:"); [recorder release]; recorder = nil; } Checking the debugger, it flags the error here @synthesize aPlayer, recorder; This is the part I don't understand. I thought it may have something to do with releasing memory but I've been careful. Have I missed something?

    Read the article

  • problem with reload data from table view after come back from another view

    - by user129677
    I have a problem in my application. Any help will be greatly appreciated. Basically it is from view A to view B, and then come back from view B. In the view A, it has dynamic data loaded in from the database, and display on the table view. In this page, it also has the edit button, not on the navigation bar. When user tabs the edit button, it goes to the view B, which shows the pick view. And user can make any changes in here. Once that is done, user tabs the back button on the navigation bar, it saves the changes into the NSUserDefaults, goes back to the view A by pop the view B. When coming back to the view A, it should get the new data from the UIUserDefaults, and it did. I user NSLog to print out to the console and it shows the correct data. Also it should invoke the viewWillAppear: method to get the new data for the table view, but it didn't. It even did not call the tableView:numberOfRowsInSection: method. I place a NSLog statement inside this method but didn't print out in the console. as the result, the view A still has the old data. the only way to get the new data in the view A is to stop and start the application. both view A and view B are the subclass of UIViewController, with UITableViewDelegate and UITableViewDataSource. here is my code in the view A : - (void)viewWillAppear:(BOOL)animated { NSLog(@"enter in Schedule2ViewController ..."); // load in data from database, and store into NSArray object //[self.theTableView reloadData]; [self.theTableView setNeedsDisplay]; //[self.theTableView setNeedsLayout]; } in here, the "theTableView" is a UITableView variable. And I try all three cases of "reloadData", "setNeedsDisplay", and "setNeedsLayout", but didn't seem to work. in the view B, here is the method corresponding to the back button on the navigation bar. - (void)viewDidLoad { UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(savePreference)]; self.navigationItem.leftBarButtonItem = saveButton; [saveButton release]; } - (IBAction) savePreference { NSLog(@"save preference."); // save data into the NSUSerDefaults [self.navigationController popViewControllerAnimated:YES]; } Am I doing in the right way? Or is there anything that I missed? Many thanks.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >