Search Results

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

Page 16/63 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • NSView only redraws on breakpoint

    - by Jacopo
    I have a custom view inside a NSPopover. It should change according to user input and it does the first time the user interact with it but it fails to redraw the following times. I have tried to put an NSLog inside the -drawRect: method and it doesn't get called during normal execution. When I try to debug and put a breakpoint inside the method it gets called normally and the app works as it should. I explicitly call the view -setNeedsDisplay: method every time I need it to redraw. I don't understand why it should make a difference. Here is the code that update the status of the view. These methods are part of the NSTextField delegate method -textDidChange: and I checked that these get called every time the user type something in the textfield associated with popover. [tokenCloud tokensToHighlight:[NSArray arrayWithObject:completeSuggestionString]]; tokenCloud.tokens = filteredTokens; [tokenCloud setNeedsDisplay:YES]; The views is a series of recessed button. The first line update the status of all the buttons in the popover and the second add or delete buttons. They both work properly because the first time they are called the view is update properly. I have also checked that both the status of the buttons in tokenCloud and its property tokens are updated correctly. The problem is that the NSView subclass, tokenCloud, doesn't redraw so the changes are not reflected in the UI the second time. Here is the draw method of the view: - (void)drawRect:(NSRect)rect { [self recalculateButtonLocations]; NSLog(@"Redrawn"); } Again this method gets called normally every time I update the view if I place a breakpoint in [self recalculateButtonLocations];. If instead I let the app run normally nothing gets logged in the console the second time I update the view. Same thing if I include the NSLog in the recalculateButtonLocations method, nothing gets logged the second time meaning that the method is not called.

    Read the article

  • How do you get and set a class property across multiple functions in Objective-C?

    - by editor
    Following up on this question about sharing objects between classes, I now need to figure out how to share the objects across various functions in a class. First, the setup: In my App Delegate I load menu information from JSON into a NSMutableDictionary and message that through to a view controller using a function called initWithData. I need to use this dictionary to populate a new Table View, which has methods like numberOfRowsInSection and cellForRowAtIndexPath. I'd like to use the dictionary count to return numberOfRowsInSection and info in the dictionary to populate each cell. Unfortunately, my code never gets beyond the init stage and the dictionary is empty so numberOfRowsInSection always returns zero. I thought I could create a class property, synthesize it and then set it. But it doesn't seem to want to retain the property's value. What am I doing wrong here? In the header .h: @interface FirstViewController:UIViewController <UITableViewDataSource, UITableViewDelegate, UITabBarControllerDelegate> { NSMutableDictionary *sectorDictionary; NSInteger sectorCount; } @property (nonatomic, retain) NSMutableDictionary *sectorDictionary; - (id)initWithData:(NSMutableDictionary*)data; @end in the implementation .m: - (id) testFunction:(NSMutableDictionary*)dictionary { NSLog(@"Count #1: %d", [dictionary count]); return nil; } - (id)initWithData:(NSMutableDictionary *)data { if (!(self=[super init])) { return nil; } [self testFunction:data]; // this is where I'd like to set a retained property self.sectorDictionary = data; return nil; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSLog(@"Count #2: %d", [self.sectorDictionary count]); return [self.sectorDictionary count]; } Output from NSLog: 2010-05-04 23:00:06.255 JSONApp[15890:207] Count #1: 9 2010-05-04 23:00:06.259 JSONApp[15890:207] Count #2: 0

    Read the article

  • Core Data to-many relationship in code

    - by Jan Bezemer
    I have three entities: Session, User and Test. A session has 0-many users and a user can perform 0-6 tests. (I say 0 but in the real application always at least 1 is required, at least 1 user for a session and at least 1 test for a user. But I say 0 to express an empty start.) All entities have their own specific data attributes too. A user has a name, A session has a name, a test has six values to be filled in by the user, and so on. But my issue is with the relationships. How do I set multiple users and have them added to one session (same goes for multiple tests for one user). How do I show the content in a right way? How do I show a session that has multiple users and these users having completed multiple tests? Here's my code so far with regard to issue 1: Session *session = [NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:context]; session.name = @"Session 1"; User *users = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context]; users.age = [NSNumber numberWithInt:28]; users.session = session; //sessie.users = users; [sessie addUserObject:users]; With regard to issue 2: I can log the session, but I can't get the user(s) logged from a session. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session" inManagedObjectContext:context]; [fetchRequest setEntity:entity]; NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; for (Session *info in fetchedObjects) { NSLog(@"Name: %@", info.name); NSLog(@"Having problems with this: %@",info.user); //User *details = info.user; //NSLog(@"User: %@", details.age); }

    Read the article

  • Pass NSURL from One Class To Another

    - by user717452
    In my appDelegate in didFinishLaunchingWithOptions, I have the following: NSURL *url = [NSURL URLWithString:@"http://www.thejenkinsinstitute.com/Journal/"]; NSString *content = [NSString stringWithContentsOfURL:url]; NSString * aString = content; NSMutableArray *substrings = [NSMutableArray new]; NSScanner *scanner = [NSScanner scannerWithString:aString]; [scanner scanUpToString:@"<p>To Download the PDF, " intoString:nil]; // Scan all characters before # while(![scanner isAtEnd]) { NSString *substring = nil; [scanner scanString:@"<p>To Download the PDF, <a href=\"" intoString:nil]; // Scan the # character if([scanner scanUpToString:@"\"" intoString:&substring]) { // If the space immediately followed the #, this will be skipped [substrings addObject:substring]; } [scanner scanUpToString:@"" intoString:nil]; // Scan all characters before next # } // do something with substrings NSString *URLstring = [substrings objectAtIndex:0]; self.theheurl = [NSURL URLWithString:URLstring]; NSLog(@"%@", theheurl); [substrings release]; The console printout for theheurl gives me a valid URL ending in .pdf. In the class I would like to load the URL, I have the following: - (void)viewWillAppear:(BOOL)animated { _appdelegate.theheurl = currentURL; NSLog(@"%@", currentURL); NSLog(@"%@", _appdelegate.theheurl); [worship loadRequest:[NSURLRequest requestWithURL:currentURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0]]; timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:@selector(tick) userInfo:nil repeats:YES]; [super viewWillAppear:YES]; } However, both NSLogs in that class come back null. What am I Doing wrong in getting the NSURL from the AppDelegate to the class to load it?

    Read the article

  • Timed selector never performed

    - by sudo rm -rf
    I've added an observer for my method: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeViewAfterUpdating) name:@"labelUpdatedShouldReturn" object:nil]; Then my relevant methods: -(void)closeViewAfterUpdating; { NSLog(@"Part 1 called"); [self performSelector:@selector(closeViewAfterUpdating2) withObject:nil afterDelay:2.0]; } -(void)closeViewAfterUpdating2; { NSLog(@"Part 2 called"); [self dismissModalViewControllerAnimated:YES]; } The only reason why I've split this method into two parts is so that I can have a delay before the method is fired. The problem is, the second method is never called. My NSLog output shows Part 1 called, but it never fires part 2. Any ideas? EDIT: I'm calling the notification from a background thread, does that make a difference by any chance? Here's how I'm creating my background thread: [NSThread detachNewThreadSelector:@selector(getWeather) toTarget:self withObject:nil]; and in getWeather I have: [[NSNotificationCenter defaultCenter] postNotificationName:@"updateZipLabel" object:textfield.text]; Also, calling: [self performSelector:@selector(closeViewAfterUpdating2) withObject:nil]; does work. EDITx2: I fixed it. Just needed to post the notification in my main thread and it worked just fine.

    Read the article

  • How to populate a core data store programmatically?

    - by jdmuys
    I have ran out of hairs to pull with a crash in this routine that populates a core data store from a 9000+ line plist file. The crash happened at the very end of the routine inside the call to [managedObjectContext save:&error]. While if I save after every object insertion, the crash doesn't happen. Of course, saving after every object insertion totally kills the performance (from less than a second to many minutes). I modified my code so that it saves every K insertions, and the crash happens as soon as K = 2. The crash is an out-of-bound exception for an NSArray: Serious application error. Exception was caught during Core Data change processing: *** -[NSCFArray objectAtIndex:]: index (1) beyond bounds (1) with userInfo (null) Also maybe relevant, when the exception happen, my fetch result controller controllerDidChangeContent: delegate routine is in the call stack. It simply calls my table view endUpdate routine. I am now running out of ideas. How am I supposed to populate a core data store with a table view? Here is the call stack: #0 0x901ca4e6 in objc_exception_throw #1 0x01d86c3b in +[NSException raise:format:arguments:] #2 0x01d86b9a in +[NSException raise:format:] #3 0x00072cb9 in _NSArrayRaiseBoundException #4 0x00010217 in -[NSCFArray objectAtIndex:] #5 0x002eaaa7 in -[UITableView(_UITableViewPrivate) _endCellAnimationsWithContext:] #6 0x002def02 in -[UITableView endUpdates] #7 0x00004863 in -[AirportViewController controllerDidChangeContent:] at AirportViewController.m:463 #8 0x01c43be1 in -[NSFetchedResultsController(PrivateMethods) _managedObjectContextDidChange:] #9 0x0001462a in _nsnote_callback #10 0x01d31005 in _CFXNotificationPostNotification #11 0x00011ee0 in -[NSNotificationCenter postNotificationName:object:userInfo:] #12 0x01ba417d in -[NSManagedObjectContext(_NSInternalNotificationHandling) _postObjectsDidChangeNotificationWithUserInfo:] #13 0x01c03763 in -[NSManagedObjectContext(_NSInternalChangeProcessing) _createAndPostChangeNotification:withDeletions:withUpdates:withRefreshes:] #14 0x01b885ea in -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] #15 0x01bbe728 in -[NSManagedObjectContext save:] #16 0x000039ea in -[AirportViewController populateAirports] at AirportViewController.m:112 Here is the code to the routine. I apologize because a number of lines are probably irrelevant, but I'd rather err on that side. The crash happens the very first time it calls [managedObjectContext save:&error]: - (void) populateAirports { NSBundle *meBundle = [NSBundle mainBundle]; NSString *dbPath = [meBundle pathForResource:@"DuckAirportsBin" ofType:@"plist"]; NSArray *initialAirports = [[NSArray alloc] initWithContentsOfFile:dbPath]; //********************************************************************************* // get existing countries NSMutableDictionary *countries = [[NSMutableDictionary alloc] initWithCapacity:200]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Country" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSError *error = nil; NSArray *values = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; if (!values) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } int numCountries = [values count]; NSLog(@"We have %d countries in store", numCountries); for (Country *aCountry in values) { [countries setObject:aCountry forKey:aCountry.code]; } [fetchRequest release]; //********************************************************************************* // read airports int numAirports = 0; int numUnsavedAirports = 0; #define MAX_UNSAVED_AIRPORTS_BEFORE_SAVE 2 numCountries = 0; for (NSDictionary *anAirport in initialAirports) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString *countryCode = [anAirport objectForKey:@"country"]; Country *thatCountry = [countries objectForKey:countryCode]; if (!thatCountry) { thatCountry = [NSEntityDescription insertNewObjectForEntityForName:@"Country" inManagedObjectContext:managedObjectContext]; thatCountry.code = countryCode; thatCountry.name = [anAirport objectForKey:@"country_name"]; thatCountry.population = 0; [countries setObject:thatCountry forKey:countryCode]; numCountries++; NSLog(@"Found %dth country %@=%@", numCountries, countryCode, thatCountry.name); } // now that we have the country, we create the airport Airport *newAirport = [NSEntityDescription insertNewObjectForEntityForName:@"Airport" inManagedObjectContext:managedObjectContext]; newAirport.city = [anAirport objectForKey:@"city"]; newAirport.code = [anAirport objectForKey:@"code"]; newAirport.name = [anAirport objectForKey:@"name"]; newAirport.country_name = [anAirport objectForKey:@"country_name"]; newAirport.latitude = [NSNumber numberWithDouble:[[anAirport objectForKey:@"latitude"] doubleValue]]; newAirport.longitude = [NSNumber numberWithDouble:[[anAirport objectForKey:@"longitude"] doubleValue]]; newAirport.altitude = [NSNumber numberWithDouble:[[anAirport objectForKey:@"altitude"] doubleValue]]; newAirport.country = thatCountry; // [thatCountry addAirportsObject:newAirport]; numAirports++; numUnsavedAirports++; if (numUnsavedAirports >= MAX_UNSAVED_AIRPORTS_BEFORE_SAVE) { if (![managedObjectContext save:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } numUnsavedAirports = 0; } [pool release]; }

    Read the article

  • iPhone crash on CoreData save

    - by davetron5000
    This is a different situation than this question, as the solution provided doesn't work and the stack is different. Periodical crash when I save data using coredata. The stack trace isn't 100% clear on where this is happening, but I'm certain it's this routine that's being called. It's either the save: in this method or the one following. Code: -(void)saveWine { if ([self validInfo]) { Wine *wine = (Wine *)wineToEdit; if (wine == nil) { wine = (Wine *)[NSEntityDescription insertNewObjectForEntityForName:@"Wine" inManagedObjectContext:self.managedObjectContext]; } wine.uuid = [Utils createUUID]; wine.name = self.wineNameField.text; wine.vineyard = self.vineyardField.text; wine.vintage = [[self numberFormatter] numberFromString:self.vintageField.text]; wine.timeStamp = [NSDate date]; wine.rating = [NSNumber numberWithInt:self.ratingControl.selectedSegmentIndex]; wine.partnerRating = [NSNumber numberWithInt:self.partnerRatingControl.selectedSegmentIndex]; wine.varietal = self.currentVarietal; wine.tastingNotes = self.currentTastingNotes; wine.dateTasted = self.currentDateTasted; wine.tastingLocation = [[ReferenceDataAccessor defaultReferenceDataAccessor] addEntityForType:TASTING_LOCATION withName:self.currentWhereTasted]; id type = [[ReferenceDataAccessor defaultReferenceDataAccessor] entityForType:WINE_TYPE withOrdinal:self.typeControl.selectedSegmentIndex]; wine.type = type; NSError *error; NSLog(@"Saving %@",wine); if (![self.managedObjectContext save:&error]) { [Utils showAlertMessage:@"There was a problem saving your wine; try restarting the app" withTitle:@"Problem saving"]; NSLog(@"Error while saving new wine %@, %@", error, [error userInfo]); } } else { NSLog(@"ERROR - someone is calling saveWine with invalid info!!"); } } Code for addEntityForType:withName:: -(id)addEntityForType:(NSString *)type withName:(NSString *)name { if ([Utils isStringBlank:name]) { return nil; } id existing = [[ReferenceDataAccessor defaultReferenceDataAccessor] entityForType:type withName:name]; if (existing != nil) { NSLog(@"%@ with name %@ already exists",type,name); return existing; } NSManagedObject *newEntity = [NSEntityDescription insertNewObjectForEntityForName:type inManagedObjectContext:self.managedObjectContext]; [newEntity setValue:name forKey:@"name"]; NSError *error; if (![self.managedObjectContext save:&error]) { [Utils showAlertMessage:[NSString stringWithFormat:@"There was a problem saving a %@",type] withTitle:@"Database Probem"]; [Utils logErrorFully:error forOperation:[NSString stringWithFormat:@"saving new %@",type ]]; } return newEntity; } Stack trace: Thread 0 Crashed: 0 libSystem.B.dylib 0x311de2d4 __kill + 8 1 libSystem.B.dylib 0x311de2c4 kill + 4 2 libSystem.B.dylib 0x311de2b6 raise + 10 3 libSystem.B.dylib 0x311f2d72 abort + 50 4 libstdc++.6.dylib 0x301dea20 __gnu_cxx::__verbose_terminate_handler() + 376 5 libobjc.A.dylib 0x319a2594 _objc_terminate + 104 6 libstdc++.6.dylib 0x301dcdf2 __cxxabiv1::__terminate(void (*)()) + 46 7 libstdc++.6.dylib 0x301dce46 std::terminate() + 10 8 libstdc++.6.dylib 0x301dcf16 __cxa_throw + 78 9 libobjc.A.dylib 0x319a14c4 objc_exception_throw + 64 10 CoreData 0x3526e83e -[NSManagedObjectContext save:] + 1098 11 Wine Brain 0x0000651e 0x1000 + 21790 12 Wine Brain 0x0000525c 0x1000 + 16988 13 Wine Brain 0x00004894 0x1000 + 14484 14 Wine Brain 0x00008716 0x1000 + 30486 15 CoreFoundation 0x31477fe6 -[NSObject(NSObject) performSelector:withObject:withObject:] + 18 16 UIKit 0x338c14a6 -[UIApplication sendAction:to:from:forEvent:] + 78 17 UIKit 0x3395c7ae -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 86 18 CoreFoundation 0x31477fe6 -[NSObject(NSObject) performSelector:withObject:withObject:] + 18 19 UIKit 0x338c14a6 -[UIApplication sendAction:to:from:forEvent:] + 78 20 UIKit 0x338c1446 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 26 21 UIKit 0x338c1418 -[UIControl sendAction:to:forEvent:] + 32 22 UIKit 0x338c116a -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 350 23 UIKit 0x338c19c8 -[UIControl touchesEnded:withEvent:] + 336 24 UIKit 0x338b734e -[UIWindow _sendTouchesForEvent:] + 362 25 UIKit 0x338b6cc8 -[UIWindow sendEvent:] + 256 26 UIKit 0x338a1fc0 -[UIApplication sendEvent:] + 292 27 UIKit 0x338a1900 _UIApplicationHandleEvent + 5084 28 GraphicsServices 0x35d66efc PurpleEventCallback + 660 29 CoreFoundation 0x314656f8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 20 30 CoreFoundation 0x314656bc __CFRunLoopDoSource1 + 160 31 CoreFoundation 0x31457f76 __CFRunLoopRun + 514 32 CoreFoundation 0x31457c80 CFRunLoopRunSpecific + 224 33 CoreFoundation 0x31457b88 CFRunLoopRunInMode + 52 34 GraphicsServices 0x35d664a4 GSEventRunModal + 108 35 GraphicsServices 0x35d66550 GSEventRun + 56 36 UIKit 0x338d5322 -[UIApplication _run] + 406 37 UIKit 0x338d2e8c UIApplicationMain + 664 38 Wine Brain 0x000021ba 0x1000 + 4538 39 Wine Brain 0x00002184 0x1000 + 4484 I have no idea why my app's memory locations aren't being symbolocated, but the code paths lead to only two manavedObjectContext save: calls. The time this happend, addEntityForType was called all the way through, creating a new object for the "whereTasted" entity, before the final save: on the entire wine object. When I go through the same procedure again, it works fine. This leads me to believe it's something to do with the app having been run for a while when adding a new location, but I'm not sure. Any thoughts on how I can debug this and get more info the next time this happens?

    Read the article

  • How do I use UIImagePickerController just to display the camera and not take a picture?

    - by Thomas
    Hello All: I'd like to know how to open the camera inside of a pre-defined frame (not the entire screen). When the view loads, I have a box, and inside it, I want to display what the camera sees. I don't want to snap a picture, just basically use the camera as a viewfinder. I have searched this site and have not yet found what I'm looking for. Please help. Thanks! Thomas Update 1: Here is what I have tried so far. 1.) I added UIImageView to my xib. 2.) Connect the following outlet to the UIImageView in IB IBOutlet UIImageView *cameraWindow; 3.) I put the following code in viewWillAppear -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; picker.sourceType = UIImagePickerControllerSourceTypeCamera; [self presentModalViewController:picker animated:YES]; NSLog(@"viewWillAppear ran"); } But this method does not run, as evident by the absence of NSLog statement from my console. Please help! Thanks, Thomas Update 2: OK I got it to run by putting the code in viewDidLoad but my camera still doesn't show up...any suggestions? Anyone....? I've been reading the UIImagePickerController class reference, but am kinda unsure how to make sense of it. I'm still learning iPhone, so it's a bit of a struggle. Please help! - (void)viewDidLoad { [super viewDidLoad]; // Create a bool variable "camera" and call isSourceTypeAvailable to see if camera exists on device BOOL camera = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]; // If there is a camera, then display the world throught the viewfinder if(camera) { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; // Since I'm not actually taking a picture, is a delegate function necessary? picker.delegate = self; picker.sourceType = UIImagePickerControllerSourceTypeCamera; [self presentModalViewController:picker animated:YES]; NSLog(@"Camera is available"); } // Otherwise, do nothing. else NSLog(@"No camera available"); } Thanks! Thomas Update 3: A-HA! Found this on the Apple Class Reference. Discussion The delegate receives notifications when the user picks an image or movie, or exits the picker interface. The delegate also decides when to dismiss the picker interface, so you must provide a delegate to use a picker. If this property is nil, the picker is dismissed immediately if you try to show it. Gonna play around with the delegate now. Then I'm going to read on wtf a delegate is. Backwards? Whatever :-p Update 4: The two delegate functions for the class are – imagePickerController:didFinishPickingMediaWithInfo: – imagePickerControllerDidCancel: and since I don't actually want to pick an image or give the user the option to cancel, I am just defining the methods. They should never run though....I think.

    Read the article

  • Cocoa nextEventMatchingMask not receiving NSMouseMoved event

    - by Jonny
    Hello, I created a local event loop and showed up a borderless window (derived from NSPanel), I found in the event loop there's no NSMouseMoved event received, although I can receive Mouse button down/up events. What should I do to get the NSMouseMoved events? I found making the float window as key window can receive the NSMouseMoved events, but I don't want to change key window. And it appears this is possible, because I found after clicking the test App Icon in System Dock Bar, I can receive the mousemoved events, and the key window/mainwindow are unchanged. Here's the my test code: (Create a Cocoa App project names FloatWindowTest, and put a button to link it with the onClick: IBAction). Thanks in advance! -Jonny #import "FloatWindowTestAppDelegate.h" @interface FloatWindow : NSPanel @end @interface FloatWindowContentView : NSView @end @implementation FloatWindowTestAppDelegate @synthesize window; - (void)delayedAction:(id)sender { // What does this function do? // 1. create a float window // 2. create a local event loop // 3. print out the events got from nextEventMatchingMask. // 4. send it to float window. // What is the problem? // In local event loop, althrough the event mask has set NSMouseMovedMask // there's no mouse moved messages received. // FloatWindow* floatWindow = [[FloatWindow alloc] init]; NSEvent* event = [NSApp currentEvent]; NSPoint screenOrigin = [[self window] convertBaseToScreen:[event locationInWindow]]; [floatWindow setFrameTopLeftPoint:screenOrigin]; [floatWindow orderFront:nil]; //Making the float window as Key window will work, however //change active window is not anticipated. //[floatWindow makeKeyAndOrderFront:nil]; BOOL done = NO; while (!done) { NSAutoreleasePool* pool = [NSAutoreleasePool new]; NSUInteger eventMask = NSLeftMouseDownMask| NSLeftMouseUpMask| NSMouseMovedMask| NSMouseEnteredMask| NSMouseExitedMask| NSLeftMouseDraggedMask; NSEvent* event = [NSApp nextEventMatchingMask:eventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES]; //why I cannot get NSMouseMoved event?? NSLog(@"new event %@", [event description]); [floatWindow sendEvent:event]; [pool drain]; } [floatWindow release]; return; } -(IBAction)onClick:(id)sender { //Tried to postpone the local event loop //after return from button's mouse tracking loop. //but not fixes this problem. [[NSRunLoop currentRunLoop] performSelector:@selector(delayedAction:) target:self argument:nil order:0 modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]]; } @end @implementation FloatWindow - (id)init { NSRect contentRect = NSMakeRect(200,300,200,300); self = [super initWithContentRect:contentRect styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:YES]; if (self) { [self setLevel:NSFloatingWindowLevel]; NSRect frameRect = [self frameRectForContentRect:contentRect]; NSView* view = [[[FloatWindowContentView alloc] initWithFrame:frameRect] autorelease]; [self setContentView:view]; [self setAcceptsMouseMovedEvents:YES]; [self setIgnoresMouseEvents:NO]; } return self; } - (BOOL)becomesKeyOnlyIfNeeded { return YES; } - (void)becomeMainWindow { NSLog(@"becomeMainWindow"); [super becomeMainWindow]; } - (void)becomeKeyWindow { NSLog(@"becomeKeyWindow"); [super becomeKeyWindow]; } @end @implementation FloatWindowContentView - (BOOL)acceptsFirstMouse:(NSEvent *)theEvent { return YES; } - (BOOL)acceptsFirstResponder { return YES; } - (id)initWithFrame:(NSRect)frameRect { self = [super initWithFrame:frameRect]; if (self) { NSTrackingArea* area; area = [[NSTrackingArea alloc] initWithRect:frameRect options:NSTrackingActiveAlways| NSTrackingMouseMoved| NSTrackingMouseEnteredAndExited owner:self userInfo:nil]; [self addTrackingArea:area]; [area release]; } return self; } - (void)drawRect:(NSRect)rect { [[NSColor redColor] set]; NSRectFill([self bounds]); } - (BOOL)becomeFirstResponder { NSLog(@"becomeFirstResponder"); return [super becomeFirstResponder]; } @end

    Read the article

  • Why does Keychain Services return the wrong keychain content?

    - by Graham Lee
    I've been trying to use persistent keychain references in an iPhone application. I found that if I created two different keychain items, I would get a different persistent reference each time (they look like 'genp.......1', 'genp.......2', …). However, attempts to look up the items by persistent reference always returned the content of the first item. Why should this be? I confirmed that my keychain-saving code was definitely creating new items in each case (rather than updating existing items), and was not getting any errors. And as I say, Keychain Services is giving a different persistent reference for each item. I've managed to solve my immediate problem by searching for keychain items by attribute rather than persistent references, but it would be easier to use persistent references so I'd appreciate solving this problem. Here's my code: - (NSString *)keychainItemWithName: (NSString *)name { NSString *path = [GLApplicationSupportFolder() stringByAppendingPathComponent: name]; NSData *persistentRef = [NSData dataWithContentsOfFile: path]; if (!persistentRef) { NSLog(@"no persistent reference for name: %@", name); return nil; } NSArray *refs = [NSArray arrayWithObject: persistentRef]; //get the data CFMutableDictionaryRef params = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue(params, kSecMatchItemList, refs); CFDictionaryAddValue(params, kSecClass, kSecClassGenericPassword); CFDictionaryAddValue(params, kSecReturnData, kCFBooleanTrue); CFDataRef item = NULL; OSStatus result = SecItemCopyMatching(params, (CFTypeRef *)&item); CFRelease(params); if (result != errSecSuccess) { NSLog(@"error %d retrieving keychain reference for name: %@", result, name); return nil; } NSString *token = [[NSString alloc] initWithData: (NSData *)item encoding: NSUTF8StringEncoding]; CFRelease(item); return [token autorelease]; } - (void)setKeychainItem: (NSString *)newToken forName: (NSString *)name { NSData *tokenData = [newToken dataUsingEncoding: NSUTF8StringEncoding]; //firstly, find out whether the item already exists NSDictionary *searchAttributes = [NSDictionary dictionaryWithObjectsAndKeys: name, kSecAttrAccount, kCFBooleanTrue, kSecReturnAttributes, nil]; NSDictionary *foundAttrs = nil; OSStatus searchResult = SecItemCopyMatching((CFDictionaryRef)searchAttributes, (CFTypeRef *)&foundAttrs); if (noErr == searchResult) { NSMutableDictionary *toStore = [foundAttrs mutableCopy]; [toStore setObject: tokenData forKey: (id)kSecValueData]; OSStatus result = SecItemUpdate((CFDictionaryRef)foundAttrs, (CFDictionaryRef)toStore); if (result != errSecSuccess) { NSLog(@"error %d updating keychain", result); } [toStore release]; return; } //need to create the item. CFMutableDictionaryRef params = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue(params, kSecClass, kSecClassGenericPassword); CFDictionaryAddValue(params, kSecAttrAccount, name); CFDictionaryAddValue(params, kSecReturnPersistentRef, kCFBooleanTrue); CFDictionaryAddValue(params, kSecValueData, tokenData); NSData *persistentRef = nil; OSStatus result = SecItemAdd(params, (CFTypeRef *)&persistentRef); CFRelease(params); if (result != errSecSuccess) { NSLog(@"error %d from keychain services", result); return; } NSString *path = [GLApplicationSupportFolder() stringByAppendingPathComponent: name]; [persistentRef writeToFile: path atomically: NO]; [persistentRef release]; }

    Read the article

  • "didChangeSection:" NSfetchedResultsController delegate method not being called

    - by robenk
    I have a standard split view controller, with a detail view and a table view. Pressing a button in the detail view can cause the an object to change its placement in the table view's ordering. This works fine, as long as the resulting ordering change doesn't result in a section being added or removed. I.e. an object can change it's ordering in a section or switch from one section to another. Those ordering changes work correctly without problems. But, if the object tries to move to a section that doesn't exist yet, or is the last object to leave a section (therefore requiring the section its leaving to be removed), then the application crashes. NSFetchedResultsControllerDelegate has methods to handle sections being added and removed that should be called in those cases. But those delegate methods aren't being called for some reason. The code in question, is boilerplate: - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { NSLog(@"willChangeContent"); [self.tableView beginUpdates]; } - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { NSLog(@"didChangeSection"); switch(type) { case NSFetchedResultsChangeInsert: [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { NSLog(@"didChangeObject"); UITableView *tableView = self.tableView; switch(type) { case NSFetchedResultsChangeInsert: [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeUpdate: [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; break; case NSFetchedResultsChangeMove: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { NSLog(@"didChangeContent"); [self.tableView endUpdates]; [detailViewController.reminderView update]; } Starting the application, and then causing the last object to leave a section results in the following output: 2011-01-08 23:40:18.910 Reminders[54647:207] willChangeContent 2011-01-08 23:40:18.912 Reminders[54647:207] didChangeObject 2011-01-08 23:40:18.914 Reminders[54647:207] didChangeContent 2011-01-08 23:40:18.915 Reminders[54647:207] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1145.66/UITableView.m:825 2011-01-08 23:40:18.917 Reminders[54647:207] Serious application error. Exception was caught during Core Data change processing: Invalid update: invalid number of sections. The number of sections contained in the table view after the update (5) must be equal to the number of sections contained in the table view before the update (6), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted). with userInfo (null) As you can see, "willChangeContent", "didChangeObject" (moving the object in question), and "didChangeContent" were all called properly. Based on the Apple's NSFetchedResultsControllerDelegate documentation "didChangeSection" should have been called before "didChangeObject", which would have prevented the exception causing the crash. So I guess the question is how do I assure that didChangeSection gets called? Thanks in advance for any help!

    Read the article

  • Problem with parsing strings

    - by Peter Small
    I am trying to put a line of dialog on each of a series of images. To match the dialog line with the correct image, I end each line with a forward slash (/) followed by a number to identify the matching image. I then parse each line to get the dialog and then the reference number for the image. It all works fine except that when I put the dialog line into a textView I get the whole line in the textView instead of the dialog part. What is confusing is that the console seems to indicate that the parsing of the dialog line has been carried out correctly. Here are the details of my coding: @interface DialogSequence_1ViewController : UIViewController { IBOutlet UIImageView *theImage; IBOutlet UITextView *fullDialog; IBOutlet UITextView *selectedDialog; IBOutlet UIButton *test_1; IBOutlet UIButton *test_2; IBOutlet UIButton *test_3; NSArray *arrayLines; IBOutlet UISlider *readingSpeed; NSArray *cartoonViews; NSMutableString *dialog; NSMutableArray *dialogLineSections; int lNum; } @property (retain,nonatomic) UITextView *fullDialog; @property (retain,nonatomic) UITextView *selectedDialog; @property (retain,nonatomic) UIButton *test_1; @property (retain,nonatomic) UIButton *test_2; @property (retain,nonatomic) UIButton *test_3; @property (retain,nonatomic) NSArray *arrayLines; @property (retain,nonatomic) NSMutableString *dialog; @property (retain,nonatomic) NSMutableArray *dialogLineSections; @property (retain,nonatomic) UIImageView *theImage; @property (retain,nonatomic) UISlider *readingSpeed; -(IBAction)start:(id)sender; -(IBAction)counter:(id)sender; -(IBAction)runNextLine:(id)sender; @end @implementation DialogSequence_1ViewController @synthesize fullDialog; @synthesize selectedDialog; @synthesize test_1; @synthesize test_2; @synthesize test_3; @synthesize arrayLines; @synthesize dialog; @synthesize theImage; @synthesize readingSpeed; @synthesize dialogLineSections; -(IBAction)runNextLine:(id)sender{ //Get dialog line to display from the arrayLines array NSMutableString *dialogLineDetails; dialogLineDetails =[arrayLines objectAtIndex:lNum]; NSLog(@"dialogLineDetails = %@",dialogLineDetails); //Parse the dialog line dialogLineSections = [dialogLineDetails componentsSeparatedByString: @"/"]; selectedDialog.text =[dialogLineSections objectAtIndex: 0]; NSLog(@"Dialog part of line = %@",[dialogLineSections objectAtIndex: 0]); NSMutableString *imageBit; imageBit = [dialogLineSections objectAtIndex: 1]; NSLog(@"Image code = %@",imageBit); //Select right image int im = [imageBit intValue]; NSLog(@"imageChoiceInteger = %i",im); //------more code } I get a warning on the line: dialogLineSections = [dialogLineDetails componentsSeparatedByString: @"/"]; warning: incompatible Objective-C types assigning 'struct NSArray *', expected 'struct NSMutableArray *' I don't quite understand this and have tried to change the types but to no avail. Would be grateful for some advice here.

    Read the article

  • Memory management in iphone cocos2d

    - by muthu
    i am iphone developer very new to this field....i am developing a ebook app in iphone using cocos2d...i use more than 150 images(i guess) the problem while turning from one page to another images get hanged randomly...... i tried this also [[TextureMgr sharedTextureMgr] removeAllTextures]; but went in vain...i guess the the problem is with the memory.....this my coding for all the pages -(id)init { if( (self=[super init] )) { self.isTouchEnabled = YES; [SimpleAudioEngine sharedEngine]; NSLog(@"b4 cover"); Sprite *bg1 = [Sprite spriteWithFile:@"a.jpg"]; bg1.anchorPoint = CGPointZero; [self addChild:bg1 z:-1]; once = TRUE; soundId = [[SimpleAudioEngine sharedEngine] playEffect:@".mp3"]; } return self; } -(void) transitionfront:(id) sender { [[SimpleAudioEngine sharedEngine] stopEffect:soundId]; soundId1 = [[SimpleAudioEngine sharedEngine] playEffect:@"page_turn.mp3"]; flip = [[Sprite spriteWithFile:@"a.jpg"] retain]; [self addChild: flip z:1]; [flip setPosition:ccp(160,240)]; Animation* animation1 = [Animation animationWithName:@"Page1" delay:0.09]; for( int i=1;i<4;i++) [animation1 addFrameWithFilename: [NSString stringWithFormat:@".jpg", i]]; id action = [Animate actionWithAnimation: animation1]; //id action = [RepeatForever actionWithAction:[Animate actionWithAnimation: animation1]]; [flip runAction:action]; [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(moveforward) userInfo:nil repeats:NO]; } -(void) moveforward { [[SimpleAudioEngine sharedEngine] stopEffect:soundId1]; [[Director sharedDirector] replaceScene: [ [Scene node] addChild: [nextpage node] z:0] ]; } -(void) transitionback:(id) sender { [[SimpleAudioEngine sharedEngine] stopEffect:soundId]; soundId1 = [[SimpleAudioEngine sharedEngine] playEffect:@".mp3"]; flip = [[Sprite spriteWithFile:@".jpg"] retain]; [self addChild: flip z:1]; [flip setPosition:ccp(160,240)]; Animation* animation1 = [Animation animationWithName:@"Page1" delay:0.09]; for( int i=3;i>0;i--) [animation1 addFrameWithFilename: [NSString stringWithFormat:@".jpg", i]]; id action = [Animate actionWithAnimation: animation1]; //id action = [RepeatForever actionWithAction:[Animate actionWithAnimation: animation1]]; [flip runAction:action]; [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(movebackward) userInfo:nil repeats:NO]; } -(void) movebackward{ //[[SimpleAudioEngine sharedEngine]stopEffect:@".mp3"]; [[Director sharedDirector]replaceScene:[[Scene node]addChild:[b4page node] z:0]]; } -(void) glossary :(id) sender { [[SimpleAudioEngine sharedEngine]stopEffect:soundId]; [[Director sharedDirector]replaceScene:[[Scene node]addChild:[ node] z:0]]; } -(BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint cocosTouchPoint = [touch locationInView: [touch view]]; CGPoint point = [[Director sharedDirector] convertToGL:cocosTouchPoint]; NSLog(@"pointx: %f pointy:%f", point.x, point.y); // Was a tab touched, if so, which one... if (CGRectContainsPoint(CGRectMake(220, 0, 100, 70), point)) { if(once) { NSLog(@"enterred page1"); [self transitionfront:nil]; once = FALSE; } } if (CGRectContainsPoint(CGRectMake(0,0,60,60), point)) { if(once) { NSLog(@"enterred cover"); [self transitionback:nil]; once = FALSE; } } if (CGRectContainsPoint(CGRectMake(100, 15, 30, 30), point)) { if(once){ [self glossary :nil]; once = FALSE; } } return kEventHandled; } -(void)playEffect:(NSString*)sound{ if(effectPlayer!=nil){ [effectPlayer release]; } NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:sound ofType:@"mp3"]]; effectPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [effectPlayer setDelegate:self]; [effectPlayer play]; } -(void)stopEffect { [effectPlayer stop]; } -(void) dealloc{ [super dealloc]; } do pls help me........ do give me a exact coding this is the err..... *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: aesop.mp3)' 2010-05-27 10:43:09.834 abc[276:20b] Stack: ( 11674715, 2476006971, 11758651, 11758490, 5126917, 660698, 660881, 661061, 131577, 448857, 120432, 153433, 630890, 23694899, 23603228, 23630005, 47120081, 11459456, 11455560, 47114125, 47114322, 23633923, 9928, 9814 )

    Read the article

  • CFStrings and storing them into models, related topics

    - by Jasconius
    I have a very frustrating issue that I believe involves CFStringRef and passing them along to custom model properties. The code is pretty messy right now as I am in a debug state, but I will try to describe the problem in words as best as I can. I have a custom model, User, which for irrelevant reasons, I am storing CF types derived from the Address Book API into. Examples include: Name, email as NSStrings. I am simply retrieving the CFStringRef value from the AddressBook API and casting as a string, whereupon I assign to the custom model instance and then CFRelease the string. These NSString properties are set as (nonatomic, retain). I then store this model into an NSArray, and I use this Array as a datasource for a UITableView When accessing the object in the cellForRowAtIndexPath, I get a memory access error. When I do a Debug, I see that the value for this datasource array appears at first glance to be corrupted. I've seen strange values assigned to it, including just plain strings, such as one that I fed to an NSLog function in earlier in the method. So, the thing that leads me to believe that this is Core Foundation related is that I am executing this exact same code, in the same class even, on non-Address Book data, in fact, just good old JSON parsed strings, which produce true Cocoa NSStrings, that I follow the same exact steps to create the datasource array. This code works fine. I have a feeling that my (retain) property declaration and/or my [stringVar release] in my custom model dealloc method may be causing memory problems (since it is my understanding that you shouldn't call a Cocoa retain or release on a CF object). Here is the code. I know some of this is super-roundabout but I was trying to make things as explicit as possible for the sake of debugging. NSMutableArray *friendUsers = [[NSMutableArray alloc] init]; int numberOfPeople = CFArrayGetCount(people); for (int i = 0; i < numberOfPeople; i++) { ABMutableMultiValueRef emails = ABRecordCopyValue(CFArrayGetValueAtIndex(people, i), kABPersonEmailProperty); if (ABMultiValueGetCount(emails) > 0) { User *addressContact = [[User alloc] init]; NSString *firstName = (NSString *)ABRecordCopyValue(CFArrayGetValueAtIndex(people, i), kABPersonFirstNameProperty); NSString *lastName = (NSString *)ABRecordCopyValue(CFArrayGetValueAtIndex(people, i), kABPersonLastNameProperty); NSLog(@"%@ and %@", firstName, lastName); NSString *fullName = [NSString stringWithFormat:@"%@ %@", firstName, lastName]; NSString *email = [NSString stringWithFormat:@"%@", (NSString *)ABMultiValueCopyValueAtIndex(emails, 0)]; NSLog(@"the email: %@", email); [addressContact setName:fullName]; [addressContact setEmail:email]; [friendUsers addObject:addressContact]; [firstName release]; [lastName release]; [email release]; [addressContact release]; } CFRelease(emails); } NSLog(@"friend count: %d", [friendUsers count]); abFriends = [NSArray arrayWithArray:friendUsers]; [friendUsers release]; All of that works, every logging statement returns as expected. But when I use abFriends as a datasource, poof. Dead. Is my approach all wrong? Any advice?

    Read the article

  • Ho can I tell when the background is touched on a UICollectionView?

    - by Mason Cloud
    I've tried subclassing UICollectionView and overriding touchesBegan:withEvent: and hitTest:WithEvent:, and both of those methods trigger when I touch a cell. However, if I touch the space between the cells, nothing happens at all. Here's what I've created: @interface WSImageGalleryCollectionView : UICollectionView @end ..and.. @implementation WSImageGalleryCollectionView - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"Touches began"); [super touchesBegan:touches withEvent:event]; } - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { NSLog(@"Hit test reached"); return [super hitTest:point withEvent:event]; } @end

    Read the article

  • Why does fileURLWithPath: give me a file://localhost/ URL?

    - by jxpx777
    I have a project I'm working on and this seems like the simplest thing in the world, but the +[NSURL fileURLWithPath:] factory method is returning a strange URL. I created an empty sample project to isolate the problem and in my app delegate's applicationDidFinishLaunching: method I have this simple code: NSString *path = [@"~/Documents" stringByExpandingTildeInPath]; NSURL *url = [NSURL fileURLWithPath:path]; NSLog(@"%@ | %@", path, url); and the NSLog result looks like this: /Users/myusername/Documents | file://localhost/Users/myusername/Documents/ when I would expect the URL to be file:///Users/myusername/Documents. Any thoughts on why this is behaving like this? (10.6.3 in case it matters.)

    Read the article

  • Cannot get UISearchBar Scope Bar to appear in Toolbar on iPad

    - by Jann
    This is really causing me fits. I put a toolbar on the IUView on the iPad. I added the following: Search Bar (not Search Bar and Search Display) to the toolbar. I set the options to be as follows: Show Cancel Button, Show Scope Bar, Scope Button Titles are: "Title1" and "Title2" (with Title2's radio button selected). Opaque, Clear Context and Auto Resize are checked. I hooked up the delegate of Search Bar to the "File's Owner" and linked it to IBOutlet theSearchBar. In my viewWillAppear I have the following: [theSearchBar setScopeButtonTitles:[NSArray arrayWithObjects:@"Near Me",@"Everywhere",nil]]; //Just in case: [theSearchBar setShowsScopeBar:YES]; //doesn't seem to do anything: //[theSearchBar sizeToFit]; searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:theSearchBar contentsController:self]; [self setSearchDisplayController:searchDisplayController]; [searchDisplayController setDelegate:self]; [searchDisplayController setSearchResultsDataSource:self]; //again--does not seem to do anything..but people have suggested it: [theSearchBar sizeToFit]; Okay, so far, I thought, so good. So, I made the File's Owner .m file to be a delegate for: UISearchBarDelegate, UISearchDisplayDelegate. My issue: I have yet to implement the delegates necessary to do the search but still... shouldn't I be seeing the scopeBar next to the search field when I click into the search field? Just so you know I DO see the log of the characters I type, so the delegate is working. I have the following dummy functions in the .m file (just in case) // called when keyboard search button pressed - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { NSLog(@"Search Button Clicked\n"); [theSearchBar resignFirstResponder]; } // called when cancel button pressed - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { NSLog(@"Cancel Button Clicked\n"); [theSearchBar resignFirstResponder]; } - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { NSLog(@"Search Text So Far: '%@'\n",searchText); } - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar { return YES; } - (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar { return YES; } Why doesn't the Scope Bar appear? A results UIPopoverController appears with the title "Results" and "No results found" (of course) when i type the first character in my search...but no scope bar. (not that i expect anything other than "No Results Found". I am wondering where the scope bar is supposed to appear...in the titleView of the UIPopover? In the toolbar to the right of the search area? Where?

    Read the article

  • Why does CLLocationManager returns null locations on the iphone SDK 4 beta in the Simulator?

    - by Rigo Vides
    Hi everyone, I have this piece of code: - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"Manager did update location!!"); self.currentLocation = newLocation.description; } I have this code inside a class that conforms to the CLLocationManagerDelegate. I tested earlier in sdk 3.0 and works nice (on both simulator and device). I'm testing this class on the SDK 4, in the simulator, but it gives null as a newLocation. I can't even get the NSLog for the first call. I checked other app where I use the location framework and it doesn't work either. I implemented the locationManager:didFailWithError: message also, wich is never called. Can anyone please confirm that the simulator can't do any CLLocationManager capabilities? (a link where the bug is reported as a known issue will be awesome). Is there a way to fix this? Thanks in advance.

    Read the article

  • writing NSDictionary to plist

    - by ADude
    Hi I'm trying to write an NSDictionary to a plist but when I open the plist no data has been written to it. From the log my path looks correct and my code is pretty standard. Any ideas? NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil]; NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", @"value3", nil]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; for (id key in dictionary) { NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]); } NSString *path = [[NSBundle mainBundle] pathForResource:@"FormData" ofType:@"plist"]; NSLog(@"path:%@", path); [dictionary writeToFile:path atomically:YES];

    Read the article

  • Using the PayPal API in an iPhone application

    - by jaynaiphone
    Hello I want to use Paypal in my iphone application, I have find the soapRequest to integrating the paypal API. My code is NSString *soapMessage = [NSString stringWithFormat: @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<SOAP-ENV:Envelope xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" "<SOAP-ENV:Header>\n" "<RequesterCredentials xmlns=\"urn:ebay:api:PayPalAPI\">\n" "<Credentials xmlns=\"urn:ebay:apis:eBLBaseComponents\">\n" "<Username>api_username</Username>\n" "<Password>api_password</Password>\n" "<Signature/>\n" "<Subject/>\n" "</Credentials>\n" "</RequesterCredentials>\n" "</SOAP-ENV:Header>\n" "<SOAP-ENV:Body>\n" "<specific_api_name_Req xmlns=\"urn:ebay:api:PayPalAPI\">\n" "<specific_api_name_Request>\n" "<Version xmlns=urn:ebay:apis:eBLBaseComponents”>service_version</Version>\n" "<required_or_optional_fields xsi:type=”some_type_here”>\n" "</required_or_optional_fields>\n" "</specific_api_name_Request>\n" "</specific_api_name_Req>\n" "</SOAP-ENV:Body>\n" "</SOAP-ENV:Envelope>\n"]; NSLog(@"Soap message===%@",soapMessage); NSString *parameterString = [NSString stringWithFormat:@"USER=%@&PWD=%@&SIGNATURE=%@&VERSION=57.0&METHOD=SetMobileCheckout&AMT=%.2f&CURRENCYCODE=USD&DESC=%@&RETURNURL=%@", userName, password, signature, donationAmount, @"Some Charge", returnCallURL]; NSLog(parameterString); NSURL *url = [NSURL URLWithString:paypalUrlNVP]; NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d", [parameterString length]]; [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"]; [theRequest setHTTPMethod:@"POST"]; [theRequest setHTTPBody: [parameterString dataUsingEncoding:NSUTF8StringEncoding]]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if( theConnection ){ webData = [[NSMutableData data] retain]; // [self displayConnectingView]; }else{ NSLog(@"theConnection is NULL"); } But here I am not getting the value of paypalUrlNVP. How can i get it?? And if possible then please give some example of paypalAPI integration in iphone. I also want to use checkout functionality.I am new in this field so I have no idea about it. So, kindly give me whole sample code. Thanks in advance.

    Read the article

  • UIScrollView setZoomScale not working ?

    - by iFloh
    Hi, I am struggeling with my UIScrollview to get it to zoom-in the underlying UIImageView. In my view controller I set - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return myImageView; } In the viewDidLoad method I try to set the zoomScale to 2 as follows (note the UIImageView and Image is set in Interface Builder): - (void)viewDidLoad { [super viewDidLoad]; myScrollView.contentSize = CGSizeMake(myImageView.frame.size.width, myImageView.frame.size.height); myScrollView.contentOffset = CGPointMake(941.0, 990.0); myScrollView.minimumZoomScale = 0.1; myScrollView.maximumZoomScale = 10.0; myScrollView.zoomScale = 0.7; myScrollView.clipsToBounds = YES; myScrollView.delegate = self; NSLog(@"zoomScale: %.1f, minZoolScale: %.3f", myScrollView.zoomScale, myScrollView.minimumZoomScale); } I tried a few variations of this, but the NSLog always shows a zoomScale of 1.0. Any ideas where I screw this one up?

    Read the article

  • Operation could not be completed. AVAudioRecorder iphone SDK

    - by Jonathan
    I am trying to record using the iphones microphone: This is my code: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // the path to write file NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"testing.mp3"]; NSURL *url = [NSURL fileURLWithPath:appFile isDirectory:NO]; NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithFloat: 44100.0], AVSampleRateKey, [NSNumber numberWithInt: kAudioFormatMPEGLayer3], AVFormatIDKey, [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, [NSNumber numberWithInt: AVAudioQualityLow], AVEncoderAudioQualityKey, nil]; NSError *error; recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error]; if ([recorder prepareToRecord] == YES){ [recorder record]; }else { int errorCode = CFSwapInt32HostToBig ([error code]); NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode); } NSLog(@"BOOL = %d", (int)recorder.recording); This is the error I get: Operation could not be completed. (OSStatus error 1718449215.) And I can not work out why this doesn't work, as a lot of the code I got from a website. Jonathan

    Read the article

  • UINavigationController does not set view properties correctly when pushed

    - by Sheehan Alam
    I have a UITabBarControllerDelegate that pushes a new view controller when a certain tab is pressed: - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { MyView* myView = [[[MyView alloc] initWithNibName:@"MyView" bundle:nil]autorelease]; if([self.tabBarController.selectedViewController.title isEqualToString:@"Friends"]){ NSLog(@"Clicked Friends"); myView.reloadFriends = TRUE; [self.navigationController myView animated:YES]; } } However, if I change my code to set the tabbar's selected view controller to myView everything works, but I don't get my navigation bar: if([self.tabBarController.selectedViewController.title isEqualToString:@"Friends"]){ NSLog(@"Clicked Friends"); myView.reloadFriends = TRUE; self.tabBarController.selectedViewController = myView; } How can I set the reloadFriends property in MyView and have the navigation bar at the top?

    Read the article

  • How to select one object from a NSArray?

    - by 0SX
    First of all Merry Christmas to everyone!!! Currently I have a NSArray that has parsed content in it. When I do a NSLog of the array it prints out 20 objects with the parsed content that I needed. Like so: 2010-12-24 20:27:32.170 TestProject[48914:298] SomeContent 2010-12-24 20:27:32.172 TestProject[48914:298] SomeContent1 2010-12-24 20:27:32.172 TestProject[48914:298] SomeContent2 2010-12-24 20:27:32.173 TestProject[48914:298] SomeContent3 2010-12-24 20:27:32.173 TestProject[48914:298] SomeContent4 2010-12-24 20:27:32.173 TestProject[48914:298] SomeContent5 2010-12-24 20:27:32.174 TestProject[48914:298] SomeContent6 2010-12-24 20:27:32.175 TestProject[48914:298] SomeContent7 2010-12-24 20:27:32.176 TestProject[48914:298] SomeContent8 2010-12-24 20:27:32.176 TestProject[48914:298] SomeContent9 2010-12-24 20:27:32.177 TestProject[48914:298] SomeContent10 2010-12-24 20:27:32.177 TestProject[48914:298] SomeContent11 2010-12-24 20:27:32.177 TestProject[48914:298] SomeContent12 2010-12-24 20:27:32.179 TestProject[48914:298] SomeContent13 2010-12-24 20:27:32.179 TestProject[48914:298] SomeContent14 2010-12-24 20:27:32.180 TestProject[48914:298] SomeContent15 2010-12-24 20:27:32.180 TestProject[48914:298] SomeContent16 2010-12-24 20:27:32.181 TestProject[48914:298] SomeContent17 2010-12-24 20:27:32.181 TestProject[48914:298] SomeContent18 2010-12-24 20:27:32.190 TestProject[48914:298] SomeContent19 However, I don't need every object at once. I need to be able to pick out one object at a time so I can put each object into a string of it's own. If anyone knows a easier way to do this then what I'm trying to please let me know. Anyways, I need to be able to choose just one object depending on what object I need. For example, let's say I only need object #5 and not all the array, how can this be done so I can put it into a string? I'm thinking I might have to use the index feature but I'm not sure how to set it up properly. Here is my NSArray that I'm working with: NSArray* myArray = [document selectElements: @"div.someContent"]; NSMutableArray* results = [NSMutableArray array]; for (Element* element in myArray){ NSString* snipet = [element contentsSource]; [results addObject: snipet]; NSLog(@"%@", snipet); } NSLog(@"%i",myArray.count); I've already spent several hours trying to achieve this but my knowledge with array's is limited even with me reading the documentation. :-( Any help is much appreciated. Thanks

    Read the article

  • UIView drawRect; class variables out of scope

    - by Toby Wilson
    Short & sweet version of my last question in light of new information. I have a UIVIew with an init and a drawrect method (and another thread and a bunch of other stuff, but I'll keep it short & sweet). All of the class variables that I alloc and init in the -(id)init method are out of scope/nil/0x0 in the drawRect method, and I am unable to access them. For example; In the interface: NSObject* fred; In the implementation: -(id)init { if(self == [super init]) { fred = [[NSObject alloc] init]; } return self; } -(void)drawRect:(CGRect)rect { NSLog(@"Fred is retained %i times",[fred retainCount]); //FAIL NSLog(@"But his variable is actually just pointing at uninitialised 0x0, so you're not reading this in the debugger because the application has crashed before it got here." } Should add that init IS being called before drawRect also. Anyone have any ideas?

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >