Search Results

Search found 1009 results on 41 pages for 'nsarray'.

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

  • [NSFetchedResultsController sections] returns nil?

    - by Chris
    Hi Everyone, I am trying to resolve this for days at this stage and I'm hoping you can help. I have two ViewControllers which query two different tables from the same database using Core Data. The first ViewController is opened with the app and displays fine. The second is called from within the first ViewController, using a pretty standard fetch setup: - (NSFetchedResultsController *)fetchedClients { // Set up the fetched results controller if needed. if (fetchedClients == nil) { // Create the fetch request for the entity. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; // Edit the entity name as appropriate. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Clients" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // Edit the sort key as appropriate. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"clientsName" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; aFetchedResultsController.delegate = self; self.fetchedClients = aFetchedResultsController; [aFetchedResultsController release]; [fetchRequest release]; [sortDescriptor release]; [sortDescriptors release]; } return fetchedClients; } When I call [self.fetchedClients sections], I get a nil (0x0) return. I have examined the database using an external application to ensure data exists in the "Clients" table. Can anyone think of a reason why [self.fetchedClients sections] would return nil? Many thanks for any help you can provide. Regards, Chris

    Read the article

  • How do I set the default selection for NSTreeController at startup?

    - by John Gallagher
    The Background I've built a source list (similar to iTunes et al.) in my Cocoa app. I've got an NSOutlineView, with Value column bound to arrangedObjects.name key path of an NSTreeController. The NSTreeController accesses JGSourceListNode entities in a Core Data store. I have three subclasses of JGSourceListNode - JGProjectNode, JGGroupNode and JGFolderNode. I have selectedIndexPaths on NSTreeController bound to an NSArray called selectedIndexPaths in my App Delegate. On startup, I search for group nodes and if they're not found in the core data store I create them: if ([allGroupNodes count] == 0) { JGGroupNode *rootTrainingNode = [JGGroupNode insertInManagedObjectContext:context]; [rootTrainingNode setNodeName:@"TRAIN"]; JGProjectNode *childUntrainedNode = [JGProjectNode insertInManagedObjectContext:context]; [childUntrainedNode setParent:rootTrainingNode]; [childUntrainedNode setNodeName:@"Untrained"]; JGGroupNode *rootBrowsingNode = [JGGroupNode insertInManagedObjectContext:context]; [rootBrowsingNode setNodeName:@"BROWSE"]; JGFolderNode *childFolder = [JGFolderNode insertInManagedObjectContext:context]; [childFolder setNodeName:@"Folder"]; [childFolder setParent:rootBrowsingNode]; [context save:nil]; } What I Want When I start the app, I want both top level groups to be expanded and "Untrained" to be highlighted as shown: The Problem I put the following code in the applicationDidFinishLaunching: method of the app delegate: [sourceListOutlineView expandItem:[sourceListOutlineView itemAtRow:0]]; [sourceListOutlineView expandItem:[sourceListOutlineView itemAtRow:2]]; NSIndexPath *rootIndexPath = [NSIndexPath indexPathWithIndex:0]; NSIndexPath *childIndexPath = [rootIndexPath indexPathByAddingIndex:0]; [self setSelectedIndexPaths:[NSArray arrayWithObject:childIndexPath]]; but the outline view seems to not have been prepared yet, so this code does nothing. Ideally, eventually I want to save the last selection the user had made and restore this on a restart. The Question I'm sure it's possible using some crazy KVO to observe when the NSTreeController or NSOutlineView gets populated then expand the items and change the selection, but that feels clumsy and too much like a work around. How would I do this elegantly?

    Read the article

  • Core Data 1-to-many relationship: List all related objects as section header in UITableView

    - by Snej
    Hi: I struggle with Core Data on the iPhone about the following: I have a 1-to-many relationship in Core Data. Assume the entities are called recipe and category. A category can have many recipes. I accomplished to get all recipes listed in a UITableView with section headers named after the category. What i want to achieve is to list all categories as section header, even those which have no recipe: category1 <--- this one should be displayed too category2 recipe_x recipe_y category3 recipe_z NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Recipe" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; [fetchRequest setFetchBatchSize:10]; NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"category.categoryName" ascending:YES]; NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"recipeName" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1,sortDescriptor2, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"category.categoryName" cacheName:@"Recipes"]; What is the most elegant way to achieve this with core data?

    Read the article

  • Core data relationship memory leak

    - by cfihelp
    I have a strange (to me) memory leak when accessing an entity in a relationship. Series and Tiles have an inverse relationship to each other. // set up the fetch request NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Series" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // grab all of the series in the core data store NSError *error = nil; availableSeries = [[NSArray alloc] initWithArray:[managedObjectContext executeFetchRequest:fetchRequest error:&error]]; [fetchRequest release]; // grab one of the series Series *currentSeries = [availableSeries objectAtIndex:1]; // load all of the tiles attached to the series through the relationship NSArray *myTiles = [currentSeries.tile allObjects]; // 16 byte leak here! Instruments reports back that the final line has a 16 byte leak cause by NSPlaceHolderString. Stack trace: 2 UIKit UIApplicationMain 3 UIKit -[UIApplication _run] 4 CoreFoundation CFRunLoopRunInMode 5 CoreFoundation CFRunLoopRunSpecific 6 GraphicsServices PurpleEventCallback 7 UIKit _UIApplicationHandleEvent 8 UIKit -[UIApplication sendEvent:] 9 UIKit -[UIApplication handleEvent:withNewEvent:] 10 UIKit -[UIApplication _runWithURL:sourceBundleID:] 11 UIKit -[UIApplication _performInitializationWithURL:sourceBundleID:] 12 Memory -[AppDelegate_Phone application:didFinishLaunchingWithOptions:] /Users/cfish/svnrepo/Memory/src/Memory/iPhone/AppDelegate_Phone.m:49 13 UIKit -[UIViewController view] 14 Memory -[HomeScreenController_Phone viewDidLoad] /Users/cfish/svnrepo/Memory/src/Memory/iPhone/HomeScreenController_Phone.m:58 15 CoreData -[_NSFaultingMutableSet allObjects] 16 CoreData -[_NSFaultingMutableSet willRead] 17 CoreData -[NSFaultHandler retainedFulfillAggregateFaultForObject:andRelationship:withContext:] 18 CoreData -[NSSQLCore retainedRelationshipDataWithSourceID:forRelationship:withContext:] 19 CoreData -[NSSQLCore newFetchedPKsForSourceID:andRelationship:] 20 CoreData -[NSSQLCore rawSQLTextForToManyFaultStatement:stripBindVariables:swapEKPK:] 21 Foundation +[NSString stringWithFormat:] 22 Foundation -[NSPlaceholderString initWithFormat:locale:arguments:] 23 CoreFoundation _CFStringCreateWithFormatAndArgumentsAux 24 CoreFoundation _CFStringAppendFormatAndArgumentsAux 25 Foundation _NSDescriptionWithLocaleFunc 26 CoreFoundation -[NSObject respondsToSelector:] 27 libobjc.A.dylib class_respondsToSelector 28 libobjc.A.dylib lookUpMethod 29 libobjc.A.dylib _cache_addForwardEntry 30 libobjc.A.dylib _malloc_internal I think I'm missing something obvious but I can't quite figure out what. Thanks for your help! Update: I've copied the offending chunk of code to the first part of applicationDidFinishLaunching and it still leaks. Could there be something wrong with my model?

    Read the article

  • First Letter Section Headers with Core Data

    - by Cory Imdieke
    I'm trying to create a list of people sorted in a tableView of sections with the first letter as the title for each section - a la Address Book. I've got it all working, though there is a bit of an issue with the sort order. Here is the way I'm doing it now: NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:[NSEntityDescription entityForName:@"Contact" inManagedObjectContext:context]]; NSSortDescriptor *fullName = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:fullName, nil]; [request setSortDescriptors:sortDescriptors]; [fullName release]; [sortDescriptors release]; NSError *error = nil; [resultController release]; resultController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:@"firstLetter" cacheName:nil]; [resultController performFetch:&error]; [request release]; fullName is a standard property, and firstLetter is a transient property which returns - as you'd expect - the first letter of the fullName. 95% of the time, this works perfectly. The problem is the result controller expects these two "lists" (the sorted fullName list and the sorted firstLetter list) to match exactly. If I have 2 contacts like John and Jack, my fullName list would sort these as Jack, John every time but my firstLetter list might sort them as John, Jack sometimes as it's only sorting by the first letter and leaving the rest to chance. When these lists don't match up, I get a blank tableView with 0 items in it. I'm not really sure how I should go about fixing this issue, but it's very frustrating. Has anyone else run into this? What did you guys find out?

    Read the article

  • Issue with CAAnimation and CALayer Transforms

    - by Brian
    I have a CALayer that I want to animate across the screen. I have created two methods: one slide open the layer and one to slide close. These both work by assigning a property to the layer's transform property. Now I want to use a CAKeyFrameAnimation to slide open the layer. I got this working so the layer slides open, but now I can't slide the layer close using my old method. I am trying to figure out why this is. Any help would be great. Code: - (id)init { if( self = [super init] ) { bIsOpen = NO; closeTransform = self.transform; openTransform = CATransform3DMakeTranslation(-235.0, 0.0, 0.0); } return self; } - (void)closeMenu { if( bIsOpen ) { self.transform = closeTransform; bIsOpen = !bIsOpen; } } - (void)openMenu { if( !bIsOpen ) { CAKeyframeAnimation *closeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; closeAnimation.duration = 1.0; closeAnimation.removedOnCompletion = NO; closeAnimation.fillMode = kCAFillModeForwards; closeAnimation.values = [NSArray arrayWithObjects:[NSValue valueWithCATransform3D:closeTransform],[NSValue valueWithCATransform3D:openTransform],nil]; closeAnimation.timingFunctions = [NSArray arrayWithObject:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]]; [self addAnimation:closeAnimation forKey:@"transform"]; bIsOpen = !bIsOpen; } }

    Read the article

  • How to remove NSString Related Memory Leaks?

    - by Rahul Vyas
    in my application this method shows memory leak how do i remove leak? -(void)getOneQuestion:(int)flashcardId categoryID:(int)categoryId { flashCardText = [[NSString alloc] init]; flashCardAnswer=[[NSString alloc] init]; //NSLog(@"%s %d %s", __FILE__, __LINE__, __PRETTY_FUNCTION__, __FUNCTION__); sqlite3 *MyDatabase; sqlite3_stmt *CompiledStatement=nil; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *MyDatabasePath = [documentsDirectory stringByAppendingString:@"/flashCardDatabase.sqlite"]; if(sqlite3_open([MyDatabasePath UTF8String],&MyDatabase) == SQLITE_OK) { sqlite3_prepare_v2(MyDatabase, "select flashCardText,flashCardAnswer,flashCardTotalOption from flashcardquestionInfo where flashCardId=? and categoryId=?", -1, &CompiledStatement, NULL); sqlite3_bind_int(CompiledStatement, 1, flashcardId); sqlite3_bind_int(CompiledStatement, 2, categoryId); while(sqlite3_step(CompiledStatement) == SQLITE_ROW) { self.flashCardText = [NSString stringWithUTF8String:(char *)sqlite3_column_text(CompiledStatement,0)]; self.flashCardAnswer= [NSString stringWithUTF8String:(char *)sqlite3_column_text(CompiledStatement,1)]; flashCardTotalOption=[[NSNumber numberWithInt:sqlite3_column_int(CompiledStatement,2)] intValue]; } sqlite3_reset(CompiledStatement); sqlite3_finalize(CompiledStatement); sqlite3_close(MyDatabase); } } this method also shows leaks.....what's wrong with this method? -(void)getMultipleChoiceAnswer:(int)flashCardId { if(optionsList!=nil) [optionsList removeAllObjects]; else optionsList = [[NSMutableArray alloc] init]; sqlite3 *MyDatabase; sqlite3_stmt *CompiledStatement=nil; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *MyDatabasePath = [documentsDirectory stringByAppendingString:@"/flashCardDatabase.sqlite"]; if(sqlite3_open([MyDatabasePath UTF8String],&MyDatabase) == SQLITE_OK) { sqlite3_prepare_v2(MyDatabase,"select OptionText from flashCardMultipleAnswer where flashCardId=?", -1, &CompiledStatement, NULL); sqlite3_bind_int(CompiledStatement, 1, flashCardId); while(sqlite3_step(CompiledStatement) == SQLITE_ROW) { [optionsList addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(CompiledStatement,0)]]; } sqlite3_reset(CompiledStatement); sqlite3_finalize(CompiledStatement); sqlite3_close(MyDatabase); } }

    Read the article

  • Saving data - does work on Simulator, not on Device

    - by Peter Hajas
    I use NSData to persist an image in my application. I save the image like so (in my App Delegate): - (void)applicationWillTerminate:(UIApplication *)application { NSLog(@"Saving data"); NSData *data = UIImagePNGRepresentation([[viewController.myViewController myImage]image]); //Write the file out! NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path_to_file = [documentsDirectory stringByAppendingString:@"lastimage.png"]; [data writeToFile:path_to_file atomically:YES]; NSLog(@"Data saved."); } and then I load it back like so (in my view controller, under viewDidLoad): NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path_to_file = [documentsDirectory stringByAppendingString:@"lastimage.png"]; if([[NSFileManager defaultManager] fileExistsAtPath:path_to_file]) { NSLog(@"Found saved file, loading in image"); NSData *data = [NSData dataWithContentsOfFile:path_to_file]; UIImage *temp = [[UIImage alloc] initWithData:data]; myViewController.myImage.image = temp; NSLog(@"Finished loading in image"); } This code works every time on the simulator, but on the device, it can never seem to load back in the image. I'm pretty sure that it saves out, but I have no view of the filesystem. Am I doing something weird? Does the simulator have a different way to access its directories than the device? Thanks!

    Read the article

  • obj-c problem setting array with componentsSeperatedByString

    - by Brodie4598
    I have a data source with about 2000 lines that look like the following: 6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,United States,AKP,PAKP,68.1336,-151.743,2103,-9,A What I am interested in is the 6th section of this string so I want to turn it into an array, then i want to check the 6th section [5] for an occurrance of that string "PAKP" Code: NSBundle *bundle = [NSBundle mainBundle]; NSString *airportsPath = [bundle pathForResource:@"airports" ofType:@"dat"]; NSData *data = [NSData dataWithContentsOfFile:airportsPath]; NSString *dataString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; NSArray *dataArray = [dataString componentsSeparatedByString:@"\n"]; NSRange locationOfAirport; NSString *workingString = [[NSString alloc]initWithFormat:@""]; NSString *searchedAirport = [[NSString alloc]initWithFormat:@""]; NSString *airportData = [[NSString alloc]initWithFormat:@""]; int d; for (d=0; d < [dataArray count]; d=d+1) { workingString = [dataArray objectAtIndex:d]; testTextBox = workingString; //works correctly NSArray *workingArray = [workingString componentsSeparatedByString:@","]; testTextBox2 = [workingArray objectAtIndex: 0]; //correctly displays the first section "6712" testTextBox3 = [workingArray objectAtIndex:1] //throws exception index beyond bounds locationOfAirport = [[workingArray objectAtIndex:5] rangeOfString:@"PAKP"]; } the problem is that when the workingArray populates, it only populates with a single object (the first component of the string which is "6712". If i have it display the workingString, it correctly displays the entire string, but for some reason, it isn't correctly making the array using the commas. i tried it without using the data file and it worked fine, so the problem comes from how I am importing the data. ideas?

    Read the article

  • NSFetchedResultsController secondary sorting not working?

    - by binkly
    Hello, I'm using NSFetchedResultsController to fetch Message entities with Core Data. I want my tableview to group the messages by an attribute called ownerName. This works fine in the sense that I get a proper UI dispalying appropriately named sections. I can achieve this with the code below: NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"ownerName" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSFetchedResultsController *fetchedResultsController = nil; fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[appDelegate managedObjectContext] sectionNameKeyPath:@"ownerName" cacheName:@"Messages"] What'd I'd like to do now is have the section with the newest message at the top; exactly how it works with the Messages app on iPhone currently. I've tried adding a second sort descriptor and putting it in an array of sort descriptors and passing that to the fetchRequest but it doesn't appear to be affecting anything. Here is the 2nd sort descriptor that I used. NSSortDescriptor *idDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt" ascending:YES]; If anyone could provide some insight into this I would greatly appreciate it.

    Read the article

  • DRY Authenticated Tasks in Cocoa (with distributed objects)

    - by arbales
    I'm kind of surprise/infuriated that the only way for me to run an authenticated task, like perhaps sudo gem install shi*t, is to make a tool with pre-written code. I'm writing a MacRuby application, which doesn't seem to expose the KAuthorization* constants/methods. So.. I learned Cocoa and Objective-C. My application creates a object, serves it and calls the a tool that elevates itself and then performs a selector on a distributed object (in the tool's thread). I hoped that the distributed object's methods would evaluated inside the tool, so I could use delegation to create "privileged" tasks. If this won't work, don't try to save it, I just want a DRY/cocoa solution. AuthHelper.m //AuthorizationExecuteWithPrivileges of this. AuthResponder* my_responder = [AuthResponder sharedResponder]; // Gets the proxy object (and it's delegate) NSString *selector = [NSString stringWithUTF8String:argv[3]]; NSLog(@"Performing selector: %@", selector); setuid(0); if ([[my_responder delegate] respondsToSelector:NSSelectorFromString(selector)]){ [[my_responder delegate] performSelectorOnMainThread:NSSelectorFromString(selector) withObject:nil waitUntilDone:YES]; } RandomController.m - (void)awakeFromNib { helperToolPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/AuthHelper"]; delegatePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/ABExtensions.rb"]; AuthResponder* my_responder = [AuthResponder initAsService]; [my_responder setDelegate:self]; } -(oneway void)install_gems{ NSArray *args = [NSArray arrayWithObjects: @"gem", @"install", @"sinatra", nil]; [NSTask launchedTaskWithLaunchPath:@"/usr/bin/sudo" arguments:args]; NSLog(@"Ran AuthResponder.delegate.install_gems"); // This prints. } ... other privileges tasks. "sudo gem update --system" for one. I'm guessing the proxy object is performing the selector in it's own thread, but I want the current (privileged thread) to do it so I can use sudo. Can I force the distributed object to evaluate the selector on the tool's thread? How else can I accomplish this dryly/cocoaly?

    Read the article

  • NSTableView Drag and Drop not working

    - by macatomy
    Hi, I'm trying to set up very basic drag and drop for my NSTableView. The table view has a single column (with a custom cell). The column is bound to an NSArrayController, and the array controller's content array is bound to an NSArray on my controller object. The data displays fine in the table. I connected the dataSource and delegate outlets of the table view to my controller object, and then implemented these methods: - (BOOL)tableView:(NSTableView *)aTableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard { NSLog(@"dragging"); return YES; } - (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)op { return NSDragOperationEvery; } - (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id <NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation { return YES; } I also registered the drag types in -awakeFromNib: #define MyDragType @"MyDragType" - (void)awakeFromNib { [super awakeFromNib]; [_myTable registerForDraggedTypes:[NSArray arrayWithObjects:MyDragType, nil]]; } The problem is that the -tableView:writeRowsWithIndexes:toPasteboard: method is never called. I've looked at a bunch of examples and I can't figure out anything I'm doing wrong. Could the problem be that I'm using a custom cell? Is there something I'm supposed to override in the cell subclass to enable this functionality? EDIT: Confirmed. Switching the custom cell for a regular NSTextFieldCell made dragging work. Now, how do I make drag and drop work with my custom cell?

    Read the article

  • delete UITableView row apple addMusic example

    - by Pavan
    Hi, i am trying to add a swipe to delete feature to the addmusic example project (downloaded free from apple) so that i am able able to delete a specific row. Ive added the following code just so that i can enable to delete feature but i dont know how to remove the song from the list which i believe to be the mediaItemCollection and actually deleting it from the userMediaItemCollection which is used to queue the songs to the player. - (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath { } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { // If row is deleted, remove it from the list. if (editingStyle == UITableViewCellEditingStyleDelete) { // delete your data item here // Animate the deletion from the table. [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationFade]; } } The swipe to delete feature works nicely, the delete button only appears when swiped, but when i click delete, a SIGBART error occurs, the whole application freezes, (although the musix does continue to play, lol). Can someone please tell me how i can delete the row at that index and how i can delete it from the mediaitemcollection please. When taking that single line of code out: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationFade]; the swipe to delete works, except that it does not delete anything obviously since i havent added any actual delete functionality/coding that needs to be done. All ideas appreciated.

    Read the article

  • iPhone: variable type returned by yajl

    - by Luc
    Hello, I'm quite new to iphone programming and I want to do the following stuff: get data from a JSON REST web server parse the received data using YAJL Draw a graph with those data using core-plot So, 1th item is fine, I use ASIHttpRequest which runs as espected 3rd is almost fine (I still have to learn how to tune core-plot). The problem I have is regarding 2nd item. I use YAJL as it seems to be the faster parser, so why not give it a try :) Here is the part of code that gets the data from the server and parse them: // Get server data response_data = [request responseData]; // Parse JSON received self.arrayFromData = [response_data yajl_JSON]; NSLog(@"Array from data: %@", self.arrayFromData); The parsing works quite well in fact, the NSLog output is something like: 2010-06-14 17:56:35.375 TEST_APP[3733:207] Array from data : { data = ( { val = 1317; date = "2010-06-10T15:50:01+02:00"; }, { val = 1573; date = "2010-06-10T16:20:01+02:00"; }, ........ { val = 840; date = "2010-06-11T14:50:01+02:00"; }, { val = 1265; date = "2010-06-11T15:20:01+02:00"; } ); from = "2010-06-10T15:50:01+02:00"; to = "2010-06-11T15:20:01+02:00"; max = "2590"; } According to th yajl-objc explanations http://github.com/gabriel/yajl-objc, the parsing returns a NSArray... The thing is... I do not know how to get all the values from it as for me it looks more like a NSDictionary than a NSArray... Could you please help ? Thanks a lot, Luc edit1: it happens that this object is actually a NSCFDictionary (!), I am still not able to get value from it, when I try the objectFromKey method (that should work on a Dictionary, no ?) it fails.

    Read the article

  • XML parsing to plist iPhone SDK

    - by victor
    Hi, guys. Could you, please, help me with parsing of this XML code: <?xml version="1.0" encoding="utf-8"?> <stuff> <parts> <part id='327'> <name>Logitech MX500</name> <serial>618163558491989</serial> <account>ASDALSKD</account> <number>987 789 456</number> <alarm>alarm1</alarm> </part> <part id='846'> <name>Logitech MX510</name> <serial>871351434945431</serial> <account>KJSDAKLJFA</account> <number>454 564 131</number> <alarm>alarm2</alarm> </part> </parts> <info>Information</info> </stuff> And save data to plist file stuff.plist in this format: 327 NSArray Name NSString Logitech MX500 Serial NSString 618163558491989 Account NSString ASDALSKD Number NSString 987 789 456 Alarm NSString alarm1 846 NSArray Name NSString Logitech MX510 Serial NSString 871351434945431 Account NSString KJSDAKLJFA Number NSString 454 564 131 Alarm NSString alarm2

    Read the article

  • I don't know How to release NSString.

    - by Beomseok
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [path objectAtIndex:0]; NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"DB"]; NSString *fileName = [newWordbookName stringByAppendingString:@".csv"]; NSString *fullPath = [databasePath stringByAppendingPathComponent:fileName]; [[NSFileManager defaultManager] createFileAtPath:fullPath contents:nil attributes:nil]; [databasePath release]; //[fileName release]; Error! //[fullPath release]; Error! //NSLog(@"#1 :databasePath: %d",[databasePath retainCount]); //NSLog(@"#1 :fileName: %d",[fileName retainCount]); //NSLog(@"#1 :fullPath: %d",[fullPath retainCount]); Hi guys, I'm using this code and want to release NSString* .. so, I declare fileName, fullPath, and databasePath of NSString. But database is released, fileName, fullpath doen't release. I don't know why it happen. I know that NSArray is Autoreleased. But Is documentsDirectory autoreleased? (newWordbookName is nsstring type) I hope that I look through a document about iPhone memory management. Please advice for me.

    Read the article

  • Facebook IOS SDK: Error in Publish Story Dialog

    - by lividsquirrel
    I've successfully set up the "DemoApp" project from the Facebook IOS SDK to use my "OKC ThunderCast" Facebook application. I have also configured another "Tester" application from scratch to successfully use the Facebook SDK and publish stories to my news feed. However, in my production application, I always get this result when calling the "dialog" method. The full description of the error message is "Error on line 52 at column 17: Opening and ending tag mismatch: div line 0 and body" Here's a detailed walkthrough of all of my code to make sure nothing is missed. 1) A UIViewController calls the "authorize" method NSArray *fbPerms = [NSArray arrayWithObjects:@"read_stream", @"offline_access", nil]; [[FacebookSingleton sharedInstance].facebook authorize:fbPerms delegate:self]; Note: The FacebookSingleton is a class I wrote that always returns a single instance of the "Facebook" class. I am using it successfully in other applications. 2) Safari is opened and the user is successfully authenticated and authorized 3) The application is called back and the "handleOpenUrl" method is called, which calls the "fbDidLogin" method of the UIViewController - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { Facebook *fb = [FacebookSingleton sharedInstance].facebook; return [fb handleOpenURL:url]; } 4) The same UIViewController handles the "fbDidLogin" event, and calls the "dialog" method - (void)fbDidLogin { [[FacebookSingleton sharedInstance].facebook dialog:@"feed" andDelegate:self]; } I also have the necessary "URL Schemes" and "URL Types" entries in the .plist file. To my eyes, I am using exactly the same code in the "DemoApp", "Tester", and production applications. But while the DemoApp and Tester work, I always see this HTML error in the feed dialog in my production application. Has anyone seen a similar issue? Could it be related to the Facebook "Bundle ID" setting in the Facebook application settings? Is there some build or .plist setting that is different? I have invested a great deal of time into troubleshooting with no success in several weeks. Thanks in advance...

    Read the article

  • Multiple Application Support Directories for iPhone Simulator?

    - by Alex G
    I am developing an iPhone app with someone else. The app works fine for me, but he is running into a bug. We think this bug is related to the fact that he is getting multiple Application directories for this same app. In my ~/Library/Application Support/iPhone Simulator/User/Applications, I only have one folder at all times. He says that he will get 3 or 4 directories when he is only working on this one app. We think this is our problem because our bug has to do with displaying images that are stored in the app's Documents folder. Does anyone know why he is ending up with multiple directories or how to stop it? Edit: Here is the code for writing the image to a file: NSData *image = [NSData dataWithContentsOfURL:[NSURL URLWithString:[currentArticle articleImage]]]; NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *imagePath = [array objectAtIndex:0]; NSFileManager *NSFM = [NSFileManager defaultManager]; BOOL isDir = YES; if(![NSFM fileExistsAtPath:imagePath isDirectory:&isDir]) if(![NSFM createDirectoryAtPath:imagePath attributes:nil]) NSLog(@"error"); imagePath = [imagePath stringByAppendingFormat:@"/images"]; if(![NSFM fileExistsAtPath:imagePath isDirectory:&isDir]) if(![NSFM createDirectoryAtPath:imagePath attributes:nil]) NSLog(@"error"); imagePath = [imagePath stringByAppendingFormat:@"/%@.jpg", [currentArticle uniqueID]]; [image writeToFile:imagePath atomically:NO]; And here is the code for getting the path when I need the image: - (NSString *)imagePath { NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *imagePath = [array objectAtIndex:0]; return [imagePath stringByAppendingFormat:@"/images/%@.jpg", [self uniqueID]]; } The app works great for me, but my partner says that the images don't show up intermittently, and he notices that he gets multiple directories in his Applications folder.

    Read the article

  • Using objective-c objects with an NSDictionary

    - by Mark
    I want store a URL against a UILabel so that when a user touches the label it takes them to that URL in a UIWebView. I have declared a NSDictionary like so: NSMutableArray *linksArray = [[NSMutableArray alloc] init]; [linksArray addObject: [NSValue valueWithNonretainedObject: newsItem1ReadMoreLabel]]; [linksArray addObject: [NSValue valueWithNonretainedObject: newsItem2ReadMoreLabel]]; [linksArray addObject: [NSValue valueWithNonretainedObject: newsItem3ReadMoreLabel]]; [linksArray addObject: [NSValue valueWithNonretainedObject: newsItem4ReadMoreLabel]]; [linksArray addObject: [NSValue valueWithNonretainedObject: newsItem5ReadMoreLabel]]; //NSString *ageLink = @"http://www.theage.com.au"; NSArray *defaultLinks = [NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", nil]; self.urlToLinkDictionary = [[NSMutableDictionary alloc] init]; self.urlToLinkDictionary = [NSDictionary dictionaryWithObjects:defaultLinks forKeys:linksArray]; Considering I used a NSValue as the key, how do I get/set the URL associated with that key given that I only have references to the UILabels? this is what I have but it doesn't work: for(NSValue *key in [self.urlToLinkDictionary allKeys]) { if ([key nonretainedObjectValue] == linkedLabel) { [self.urlToLinkDictionary setValue:[newsItem link] forKey: key]; } } but I get an error: "objc_exception_throw" resolved

    Read the article

  • Does NULL and nil are equal?

    - by monish
    Hi Guys, Actually my question here is does Null and nil are equal or not? I had an Example but I am confused when they are equal when they are not. NSNull *nullValue = [NSNull null]; NSArray *arrayWithNull = [NSArray arrayWithObject:nullValue]; NSLog(@"arrayWithNull: %@", arrayWithNull); id aValue = [arrayWithNull objectAtIndex:0]; if (aValue == nil) { NSLog(@"equals nil"); } else if (aValue == [NSNull null]) { NSLog(@"equals NSNull instance"); if ([aValue isEqual:nil]) { NSLog(@"isEqual:nil"); } } Here in the above case it shows that both Null and nil are not equal and it displays "equals NSNull instance" NSString *str=NULL; id str1=nil; if(str1 == str) { printf("\n IS EQUAL........"); } else { printf("\n NOT EQUAL........"); } And in the second case it shows both are equal and it displays "IS EQUAL". Anyone's help will be much appreciated. Thank you, Monish.

    Read the article

  • Why would delaying a thread response fix view corruption?

    - by Beth S
    6 times out of 10 my very simple iPhone app is getting a corrupted display on launch or crashes randomly. But it behaves fine in the simulator. The display corruption looks like mis-colored fonts, out of place font text, wrong background colors, etc. I've found a strange work-around.. when my thread delays by 2 seconds before calling the "done" notification, everything works swimmingly. The thread reads a web page and the "done" notification loads up a PickerView with strings. So what gives? Can I not safely initiate a threaded task from viewDidLoad? - (void) loadWebPage:(NSString *)urlAddition { NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init]; NSString *pageSource; NSError *err; NSString *urlString = [NSString stringWithString:@"http://server/%@", urlAddition]; pageSource = [NSString stringWithContentsOfURL:[NSURL URLWithString: urlString] encoding:NSUTF8StringEncoding error:&err]; [NSThread sleepForTimeInterval:2.0]; // THIS STOPS THE DISPLAY CORRUPTION [[NSNotificationCenter defaultCenter] postNotificationName:@"webDoneNotification" object:nil]; [subPool drain]; } - (void) webDoneNotification: (NSNotification *)pNotification { [mediaArray release]; mediaArray = [[NSArray arrayWithObjects: [NSString stringWithString:@"new pickerview text"], nil] retain]; [mediaPickerView reloadAllComponents]; [mediaPickerView selectRow:0 inComponent:0 animated:NO]; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { mediaArray = [[NSArray arrayWithObjects: [NSString stringWithString:@"init pickerview text"], nil] retain]; if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; myWebThread = [[WebThread alloc] initWithDelegate:self]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webDoneNotification:) name:@"webDoneNotification" object:nil]; [myWebThread performSelectorInBackground:@selector(loadWebPage:) withObject:@""]; } Thanks! Update: Even a delay of 0.1 seconds is enough to completely fix the problem.

    Read the article

  • UICollectionViewCell imageView

    - by Flink
    Code works fine until I changed UIViewController with tableView to UICollectionViewController. Now all cells shows same image, sometimes it flipping to nil. However textLabels are OK. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"TourGridCell"; TourGridCell *cell = (TourGridCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; Guide *guideRecord = [self.fetchedResultsController objectAtIndexPath:indexPath]; cell.titleLabel.text = [guideRecord.name uppercaseString]; cell.titleLabel.backgroundColor = [UIColor clearColor]; if ([guideRecord.sights count] > 0) { if ([[guideRecord.sights objectAtIndex:0]valueForKey:@"thumbnail"]) { cell.imageView.image = [UIImage drawImage:[[guideRecord.sights objectAtIndex:0]valueForKey:@"thumbnail"] inImage:[UIImage imageNamed:@"MultiplePhotos"] inRect:CGRectMake(11, 11, 63, 63)]; }else { cell.imageView.image = [UIImage imageNamed:@"placeholder2"]; } NSMutableString *sightsSummary = [NSMutableString stringWithCapacity:[guideRecord.sights count]]; for (Sight *sight in guideRecord.sights) { if ([sight.name length]) { if ([sightsSummary length]) { [sightsSummary appendString:@", "]; } [sightsSummary appendString:sight.name]; } } if ([sightsSummary length]) { [sightsSummary appendString:@"."]; } cell.sightsTextLabel.text = sightsSummary; cell.detailTextLabel.text = [NSString stringWithFormat:NSLocalizedString(@"%i", nil) , [guideRecord.sights count]]; cell.detailTextLabel.hidden = NO; // cell.textLabel.alpha = 0.7; NSPredicate *enabledSightPredicate = [NSPredicate predicateWithFormat:@"notify == YES"]; NSArray *sightsEnabled = [[[guideRecord.sights array] filteredArrayUsingPredicate:enabledSightPredicate]mutableCopy]; NSPredicate *visitedSightPredicate = [NSPredicate predicateWithFormat:@"visited == YES"]; NSArray *sightsVisited = [[[guideRecord.sights array] filteredArrayUsingPredicate:visitedSightPredicate]mutableCopy]; if ([sightsEnabled count] > 0) { NSLog(@"green_badge"); cell.notifyIV.image = [UIImage imageNamed:@"green_badge"]; } else if (sightsVisited.count == 0) { NSLog(@"new_badge"); cell.notifyIV.image = [UIImage imageNamed:@"new_badge"]; } else { cell.notifyIV.image = nil; } } else { cell.notifyIV.hidden = YES; // cell.textLabel.textColor = RGB(0, 50, 140); cell.detailTextLabel.hidden = YES; cell.sightsTextLabel.text = nil; } return cell; }

    Read the article

  • Modifying NSMutableDictionary from a single index format into nested (array within array)

    - by Michael Robinson
    I need to take the member ID off the top of this and create an array inside that contains the rest of the JSON return. Here is my JSON return. [{"F_Name_VC":"Frank", "L_Name_VC":"Johnson", "userid":"18", "age":"23", },] After it is json-deserialized it looks like this: I need convert it to be transformed into this, with children sub-array: Someone else posted a similar question but without the fact that it was coming from a JSON deserialization. There were two answers but no conclusion to the question. (Answer 1): NSDictionary *item1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@" member",[NSNumber numberWithInt:3],nil] forKeys:[NSArray arrayWithObjects:@"Title",@"View",nil]]; Answer (2): NSMutableArray *Rows = [NSMutableArray arrayWithCapacity: 1]; for (int i = 0; i < 4; ++i) { NSMutableArray *theChildren = [NSMutableArray arrayWithCapacity: 1]; [theChildren addObject: [NSString stringWithFormat: @"tester %d", i]]; NSString *aTitle = [NSString stringWithFormat: @"Item %d", i]; NSDictionary *anItem = [NSDictionary dictionaryWithObjectsAndKeys: aTitle, @"Title", theChildren, @"Children"]; [Rows addObject: anItem]; } NSDictionary *Root = [NSDictionary withObject: Rows andKey: @"Rows"]; Here is my JSON return and save code: NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding]; NSError *error = nil; NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error]; if (dict) { rowsArray = [dict objectForKey:@"member"]; [rowsArray retain]; } Thanks in advance. Every tutorial on JSON only shows a simple array being returned, never with children..It's driving me crazy trying to figure this out.

    Read the article

  • Wordpress XML-RPC call from Objective C: wp.newComment

    - by radesix
    I'm using Eric Czarny's Cocoa XML-RPC framework to make a call to the Wordpress API's. I've downloaded the sample app from Wordpress which gives some good examples. Unfortunately the good examples are for every call EXCEPT wp.newComment. I'm trying to post a comment using the code below and I keep getting an error with a localized description that tells me to check my input parameters. I've checked and rechecked and I don't understand what is wrong. Any ideas? NSDictionary *commentStructure = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:0], @"comment_parent", @"xmlrpc anonymous comments plugin now enabled", @"content", @"Test Author", @"author", @"http://iphone.someurl.com", @"author_url", @"[email protected]", @"author_email", nil]; NSArray *args = [NSArray arrayWithObjects:[NSNumber numberWithInt:0], @"", @"", [NSNumber numberWithInt:[self.parentFeedItem.postID intValue]], commentStructure, nil]; // the param(s) NSString *server = [[[NSString alloc] initWithString:@"http://www.someurl.com/xmlrpc.php"] autorelease]; // the server NSString *method = [[[NSString alloc] initWithString:@"wp.newComment"] autorelease]; // the method XMLRPCRequest *request = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:server]]; [request setMethod:method withObjects:args]; id response = [self executeXMLRPCRequest:request]; [request release]; if( [response isKindOfClass:[NSError class]] ) { //return nil; NSLog(@"There was a problem"); NSLog([response localizedDescription]); }

    Read the article

  • iPhone dev: Recurse all project resoureces and collect paths

    - by thomax
    I have a bunch of HTML resources in my app organized in a hierarchy like so: dirA |---> index.html |---> a1.html |---> a2.html |---> dirB |---> b1.html |---> b2.html |---> dirC |---> c5.html |---> c19.html I'm trying to collect the absolute paths of all HTML resources however deep down, but can't seem to figure out how. So far I've tried: NSArray myPaths = [[NSBundle mainBundle] pathsForResourcesOfType:@"html" inDirectory:nil]; This returns an empty array, because I have no HTML files at the root of my project. Then there is: NSArray myPaths = [[NSBundle mainBundle] pathsForResourcesOfType:@"html" inDirectory:@"dirA"]; This returns an array containing only the paths for the three HTML resources directly below dirA. If I read the doc correctly, I guess this is to be expected; pathsForResourcesOfType does not traverse subdirectories. But is there a (preferably nice) way to do it?

    Read the article

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