Search Results

Search found 560 results on 23 pages for 'nsdictionary'.

Page 6/23 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Multiple errors while adding searching to app

    - by Thijs
    Hi, I'm fairly new at iOS programming, but I managed to make a (in my opinion quite nice) app for the app store. The main function for my next update will be a search option for the app. I followed a tutorial I found on the internet and adapted it to fit my app. I got back quite some errors, most of which I managed to fix. But now I'm completely stuck and don't know what to do next. I know it's a lot to ask, but if anyone could take a look at the code underneath, it would be greatly appreciated. Thanks! // // RootViewController.m // GGZ info // // Created by Thijs Beckers on 29-12-10. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import "RootViewController.h" // Always import the next level view controller header(s) #import "CourseCodes.h" @implementation RootViewController @synthesize dataForCurrentLevel, tableViewData; #pragma mark - #pragma mark View lifecycle // OVERRIDE METHOD - (void)viewDidLoad { [super viewDidLoad]; // Go get the data for the app... // Create a custom string that points to the right location in the app bundle NSString *pathToPlist = [[NSBundle mainBundle] pathForResource:@"SCSCurriculum" ofType:@"plist"]; // Now, place the result into the dictionary property // Note that we must retain it to keep it around dataForCurrentLevel = [[NSDictionary dictionaryWithContentsOfFile:pathToPlist] retain]; // Place the top level keys (the program codes) in an array for the table view // Note that we must retain it to keep it around // NSDictionary has a really useful instance method - allKeys // The allKeys method returns an array with all of the keys found in (this level of) a dictionary tableViewData = [[[dataForCurrentLevel allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)] retain]; //Initialize the copy array. copyListOfItems = [[NSMutableArray alloc] init]; // Set the nav bar title self.title = @"GGZ info"; //Add the search bar self.tableView.tableHeaderView = searchBar; searchBar.autocorrectionType = UITextAutocorrectionTypeNo; searching = NO; letUserSelectRow = YES; } /* - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } */ /* - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } */ /* - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } */ /* - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } */ //RootViewController.m - (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar { searching = YES; letUserSelectRow = NO; self.tableView.scrollEnabled = NO; //Add the done button. self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneSearching_Clicked:)] autorelease]; } - (NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { if(letUserSelectRow) return indexPath; else return nil; } //RootViewController.m - (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText { //Remove all objects first. [copyListOfItems removeAllObjects]; if([searchText length] &gt; 0) { searching = YES; letUserSelectRow = YES; self.tableView.scrollEnabled = YES; [self searchTableView]; } else { searching = NO; letUserSelectRow = NO; self.tableView.scrollEnabled = NO; } [self.tableView reloadData]; } //RootViewController.m - (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar { [self searchTableView]; } - (void) searchTableView { NSString *searchText = searchBar.text; NSMutableArray *searchArray = [[NSMutableArray alloc] init]; for (NSDictionary *dictionary in listOfItems) { NSArray *array = [dictionary objectForKey:@"Countries"]; [searchArray addObjectsFromArray:array]; } for (NSString *sTemp in searchArray) { NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch]; if (titleResultsRange.length &gt; 0) [copyListOfItems addObject:sTemp]; } [searchArray release]; searchArray = nil; } //RootViewController.m - (void) doneSearching_Clicked:(id)sender { searchBar.text = @""; [searchBar resignFirstResponder]; letUserSelectRow = YES; searching = NO; self.navigationItem.rightBarButtonItem = nil; self.tableView.scrollEnabled = YES; [self.tableView reloadData]; } //RootViewController.m - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { if (searching) return 1; else return [listOfItems count]; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (searching) return [copyListOfItems count]; else { //Number of rows it should expect should be based on the section NSDictionary *dictionary = [listOfItems objectAtIndex:section]; NSArray *array = [dictionary objectForKey:@"Countries"]; return [array count]; } } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { if(searching) return @""; if(section == 0) return @"Countries to visit"; else return @"Countries visited"; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } // Set up the cell... if(searching) cell.text = [copyListOfItems objectAtIndex:indexPath.row]; else { //First get the dictionary object NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; NSArray *array = [dictionary objectForKey:@"Countries"]; NSString *cellValue = [array objectAtIndex:indexPath.row]; cell.text = cellValue; } return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //Get the selected country NSString *selectedCountry = nil; if(searching) selectedCountry = [copyListOfItems objectAtIndex:indexPath.row]; else { NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; NSArray *array = [dictionary objectForKey:@"Countries"]; selectedCountry = [array objectAtIndex:indexPath.row]; } //Initialize the detail view controller and display it. DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]]; dvController.selectedCountry = selectedCountry; [self.navigationController pushViewController:dvController animated:YES]; [dvController release]; dvController = nil; } //RootViewController.m - (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar { //Add the overlay view. if(ovController == nil) ovController = [[OverlayViewController alloc] initWithNibName:@"OverlayView" bundle:[NSBundle mainBundle]]; CGFloat yaxis = self.navigationController.navigationBar.frame.size.height; CGFloat width = self.view.frame.size.width; CGFloat height = self.view.frame.size.height; //Parameters x = origion on x-axis, y = origon on y-axis. CGRect frame = CGRectMake(0, yaxis, width, height); ovController.view.frame = frame; ovController.view.backgroundColor = [UIColor grayColor]; ovController.view.alpha = 0.5; ovController.rvController = self; [self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view]; searching = YES; letUserSelectRow = NO; self.tableView.scrollEnabled = NO; //Add the done button. self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneSearching_Clicked:)] autorelease]; } // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations. return YES; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Relinquish ownership any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; } - (void)dealloc { [dataForCurrentLevel release]; [tableViewData release]; [super dealloc]; } #pragma mark - #pragma mark Table view methods // DATA SOURCE METHOD - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // DATA SOURCE METHOD - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // How many rows should be displayed? return [tableViewData count]; } // DELEGATE METHOD - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Cell reuse block static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell's contents - we want the program code, and a disclosure indicator cell.textLabel.text = [tableViewData objectAtIndex:indexPath.row]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } //RootViewController.m - (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText { //Remove all objects first. [copyListOfItems removeAllObjects]; if([searchText length] &gt; 0) { [ovController.view removeFromSuperview]; searching = YES; letUserSelectRow = YES; self.tableView.scrollEnabled = YES; [self searchTableView]; } else { [self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view]; searching = NO; letUserSelectRow = NO; self.tableView.scrollEnabled = NO; } [self.tableView reloadData]; } //RootViewController.m - (void) doneSearching_Clicked:(id)sender { searchBar.text = @""; [searchBar resignFirstResponder]; letUserSelectRow = YES; searching = NO; self.navigationItem.rightBarButtonItem = nil; self.tableView.scrollEnabled = YES; [ovController.view removeFromSuperview]; [ovController release]; ovController = nil; [self.tableView reloadData]; } // DELEGATE METHOD - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // In any navigation-based application, you follow the same pattern: // 1. Create an instance of the next-level view controller // 2. Configure that instance, with settings and data if necessary // 3. Push it on to the navigation stack // In this situation, the next level view controller is another table view // Therefore, we really don't need a nib file (do you see a CourseCodes.xib? no, there isn't one) // So, a UITableViewController offers an initializer that programmatically creates a view // 1. Create the next level view controller // ======================================== CourseCodes *nextVC = [[CourseCodes alloc] initWithStyle:UITableViewStylePlain]; // 2. Configure it... // ================== // It needs data from the dictionary - the "value" for the current "key" (that was tapped) NSDictionary *nextLevelDictionary = [dataForCurrentLevel objectForKey:[tableViewData objectAtIndex:indexPath.row]]; nextVC.dataForCurrentLevel = nextLevelDictionary; // Set the view title nextVC.title = [tableViewData objectAtIndex:indexPath.row]; // 3. Push it on to the navigation stack // ===================================== [self.navigationController pushViewController:nextVC animated:YES]; // Memory manage it [nextVC release]; } /* // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source. [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } */ /* // Override to support rearranging the table view. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ @end

    Read the article

  • Facebook event creation through iPhone app and Facebook Connect

    - by miorel
    How is this done? Is it even possible? All the function calls seem correct, but the result is always false: NSString *event = @"{\"name\":\"A party\",\"start_time\":\"1215929160\",\"end_time\":\"1215929160\",\"location\":\"Somewhere\"}"; NSDictionary *params = [NSDictionary dictionaryWithObject:event forKey:@"event_info"]; [[FBRequest requestWithDelegate:self] call:@"facebook.events.create" params:params];

    Read the article

  • Objective-C memory leak in loading remote content

    - by Ican Zilb
    I try to load a plist file from my server. I can think of 2 ways to do that, but for both Instruments says there's huge memory leak : NSData* plistData = [NSData dataWithContentsOfURL:url]; and NSDictionary* updateDigest = [NSDictionary dictionaryWithContentsOfURL: [NSURL URLWithString:updateURL] ]; The backtrace of the memory leak leads to __CFURLCache in CFNetwork and I am wondering if something can be done to fix the leak? Any other way to load a remote plist xml, without the memory leakage ? Thanks

    Read the article

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

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

    Read the article

  • Binding CoreData Managed Object to NSTextFieldCell subclass

    - by ndg
    I have an NSTableView which has its first column set to contain a custom NSTextFieldCell. My custom NSTextFieldCell needs to allow the user to edit a "desc" property within my Managed Object but to also display an "info" string that it contains (which is not editable). To achieve this, I followed this tutorial. In a nutshell, the tutorial suggests editing your Managed Objects generated subclass to create and pass a dictionary of its contents to your NSTableColumn via bindings. This works well for read-only NSCell implementations, but I'm looking to subclass NSTextFieldCell to allow the user to edit the "desc" property of my Managed Object. To do this, I followed one of the articles comments, which suggests subclassing NSFormatter to explicitly state which Managed Object property you would like the NSTextFieldCell to edit. Here's the suggested implementation: @implementation TRTableDescFormatter - (BOOL)getObjectValue:(id *)anObject forString:(NSString *)string errorDescription:(NSString **)error { if (anObject != nil){ *anObject = [NSDictionary dictionaryWithObject:string forKey:@"desc"]; return YES; } return NO; } - (NSString *)stringForObjectValue:(id)anObject { if (![anObject isKindOfClass:[NSDictionary class]]) return nil; return [anObject valueForKey:@"desc"]; } - (NSAttributedString*)attributedStringForObjectValue:(id)anObject withDefaultAttributes:(NSDictionary *)attrs { if (![anObject isKindOfClass:[NSDictionary class]]) return nil; NSAttributedString *anAttributedString = [[NSAttributedString alloc] initWithString: [anObject valueForKey:@"desc"]]; return anAttributedString; } @end I assign the NSFormatter subclass to my cell in my NSTextFieldCell subclass, like so: - (void)awakeFromNib { TRTableDescFormatter *formatter = [[[TRTableDescFormatter alloc] init] autorelease]; [self setFormatter:formatter]; } This seems to work, but falls down when editing multiple rows. The behaviour I'm seeing is that editing a row will work as expected until you try to edit another row. Upon editing another row, all previously edited rows will have their "desc" value set to the value of the currently selected row. I've been doing a lot of reading on this subject and would really like to get to the bottom of this. What's more frustrating is that my NSTextFieldCell is rendering exactly how I would like it to. This editing issue is my last obstacle! If anyone can help, that would be greatly appreciated.

    Read the article

  • Updating UISearchDisplayController with Core Data results using GCD

    - by Brian Halpin
    I'm having trouble displaying the results from Core Data in my UISearchDisplayController when I implement GCD. Without it, it works, but obviously blocks the UI. In my SearchTableViewController I have the following two methods: - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { // Tell the table data source to reload when text changes [self filterContentForSearchText:searchString]; // Return YES to cause the search result table view to be reloaded. return YES; } // Update the filtered array based on the search text -(void)filterContentForSearchText:(NSString*)searchText { // Remove all objects from the filtered search array [self.filteredLocationsArray removeAllObjects]; NSPredicate *predicate = [CoreDataMaster predicateForLocationUsingSearchText:@"Limerick"]; CoreDataMaster *coreDataMaster = [[CoreDataMaster alloc] init]; // Filter the array using NSPredicate self.filteredLocationsArray = [NSMutableArray arrayWithArray: [coreDataMaster fetchResultsFromCoreDataEntity:@"City" UsingPredicate:predicate]]; } You can probably guess that my problem is with returning the array from [coreDataMaster fetchResultsFromCoreDataEntity]. Below is the method: - (NSArray *)fetchResultsFromCoreDataEntity:(NSString *)entity UsingPredicate:(NSPredicate *)predicate { NSMutableArray *fetchedResults = [[NSMutableArray alloc] init]; dispatch_queue_t coreDataQueue = dispatch_queue_create("com.coredata.queue", DISPATCH_QUEUE_SERIAL); dispatch_async(coreDataQueue, ^{ NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entity inManagedObjectContext:self.managedObjectContext]; NSSortDescriptor *nameSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObjects:nameSort, nil]; [fetchRequest setEntity:entityDescription]; [fetchRequest setSortDescriptors:sortDescriptors]; // Check if predicate is set if (predicate) { [fetchRequest setPredicate:predicate]; } NSError *error = nil; NSArray *fetchedManagedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; for (City *city in fetchedManagedObjects) { [fetchedResults addObject:city]; } NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSArray arrayWithArray:fetchedResults] forKey:@"results"]; [[NSNotificationCenter defaultCenter] postNotificationName:@"fetchResultsComplete" object:nil userInfo:userInfo]; }); return [NSArray arrayWithArray:fetchedResults]; } So the thread hasn't finished executing by the time it returns the results to self.filteredLocationsArray. I've tried added a NSNotification which passes the NSDictionary to this method: - (void)updateSearchResults:(NSNotification *)notification { NSDictionary *userInfo = notification.userInfo; NSArray *array = [userInfo objectForKey:@"results"]; self.filteredLocationsArray = [NSMutableArray arrayWithArray:array]; [self.tableView reloadData]; } I've also tried refreshing the searchViewController like [self.searchDisplayController.searchResultsTableView reloadData]; but to no avail. I'd really appreciate it if someone could point me in the right direction and show me where I might be going wrong. Thanks

    Read the article

  • iOS: RestKit loadObject & send params

    - by Alon Amir
    using loadObjectAtResourcePath, on GET method, doesn't include my parameters on the requests. for example, i send: [RKObjectManager objectManagerWithBaseURL:@"http://something/ws"]; [[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/res" delegate:self block:^(RKObjectLoader *loader) { NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @"val", @"param1", nil]; loader.params = [RKParams paramsWithDictionary:dict]; }]; the final url request doesn't include the "?param1=val" part - why is that?

    Read the article

  • populate CoreData data model from JSON files prior to app start

    - by johannes_d
    I am creating an iPad App that displays data I got from an API in JSON format. My Core Data model has several entities(Countries, Events, Talks, ...). For each entity I have one .json file that contains all instances of the entity and its attributes as well as its relationships. I would like to populate my Core Data data model with these entities before the start of the App (otherwise it takes about 15 minutes for the iPad to create all the instances of the entities from the several JSON files using factory methods). I am currently importing the data into CoreData like this: -(void)fetchDataIntoDocument:(UIManagedDocument *)document { dispatch_queue_t dataQ = dispatch_queue_create("Data import", NULL); dispatch_async(dataQ, ^{ //Fetching data from application bundle NSURL *tedxgroupsurl = [[NSBundle mainBundle] URLForResource:@"contries" withExtension:@"json"]; NSURL *tedxeventsurl = [[NSBundle mainBundle] URLForResource:@"events" withExtension:@"json"]; //converting the JSON files to NSDictionaries NSError *error = nil; NSDictionary *countries = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:countriesurl] options:kNilOptions error:&error]; countries = [countries objectForKey:@"countries"]; NSDictionary *events = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:eventsurl] options:kNilOptions error:&error]; events = [events objectForKey:@"events"]; //creating entities using factory methods in NSManagedObject Subclasses (Country / Event) [document.managedObjectContext performBlock:^{ NSLog(@"creating countries"); for (NSDictionary *country in countries) { [Country countryWithCountryInfo:country inManagedObjectContext:document.managedObjectContext]; //creating Country entities } NSLog(@"creating events"); for (NSDictionary *event in events) { [Event eventWithEventInfo:event inManagedObjectContext:document.managedObjectContext]; // creating Event entities } NSLog(@"done creating, saving document"); [document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL]; }]; }); dispatch_release(dataQ); } This combines the different JSON files into one UIManagedDocument which i can then perform fetchRequests on to populate tableViews, mapView, etc. I'm looking for a way to create this document outside my application & add it to the mainBundle. Then I could copy it once to the apps DocumentsDirectory and be able I use it (instead of creating the Document within the app from the original JSON files). Any help is appreciated!

    Read the article

  • Error With Sending mail (kSKPSMTPPartMessageKey is nil)

    - by user1553381
    I'm trying to send mail in iPhone using "SKPSMTPMessage" and I added the libraries, In my class I added the following code: - (IBAction)sendMail:(id)sender { // if there are a connection if ([theConnection isEqualToString:@"true"]) { if ([fromEmail.text isEqualToString:@""] || [toEmail.text isEqualToString:@""]) { UIAlertView *warning = [[UIAlertView alloc] initWithTitle:@"?????" message:@"?? ??? ????? ???? ????????" delegate:self cancelButtonTitle:@"?????" otherButtonTitles:nil, nil]; [warning show]; }else { SKPSMTPMessage *test_smtp_message = [[SKPSMTPMessage alloc] init]; test_smtp_message.fromEmail = fromEmail.text; test_smtp_message.toEmail = toEmail.text; test_smtp_message.relayHost = @"smtp.gmail.com"; test_smtp_message.requiresAuth = YES; test_smtp_message.login = @"[email protected]"; test_smtp_message.pass = @"myPass"; test_smtp_message.wantsSecure = YES; NSString *subject= @"Suggest a book for you"; test_smtp_message.subject = [NSString stringWithFormat:@"%@ < %@ > ",fromEmail.text, subject]; test_smtp_message.delegate = self; NSMutableArray *parts_to_send = [NSMutableArray array]; NSDictionary *plain_text_part = [NSDictionary dictionaryWithObjectsAndKeys: @"text/plain\r\n\tcharset=UTF-8;\r\n\tformat=flowed", kSKPSMTPPartContentTypeKey, [messageBody.text stringByAppendingString:@"\n"], kSKPSMTPPartMessageKey, @"quoted-printable", kSKPSMTPPartContentTransferEncodingKey, nil]; [parts_to_send addObject:plain_text_part]; // to send attachment NSString *image_path = [[NSBundle mainBundle] pathForResource:BookCover ofType:@"jpg"]; NSData *image_data = [NSData dataWithContentsOfFile:image_path]; NSDictionary *image_part = [NSDictionary dictionaryWithObjectsAndKeys: @"inline;\r\n\tfilename=\"image.png\"",kSKPSMTPPartContentDispositionKey, @"base64",kSKPSMTPPartContentTransferEncodingKey, @"image/png;\r\n\tname=Success.png;\r\n\tx-unix-mode=0666",kSKPSMTPPartContentTypeKey, [image_data encodeWrappedBase64ForData],kSKPSMTPPartMessageKey, nil]; [parts_to_send addObject:image_part]; test_smtp_message.parts = parts_to_send; Spinner.hidden = NO; [Spinner startAnimating]; ProgressBar.hidden = NO; HighestState = 0; [test_smtp_message send]; } }else { UIAlertView *alertNoconnection = [[UIAlertView alloc] initWithTitle:@"?????" message:@"?? ???? ???? " delegate:self cancelButtonTitle:@"?????" otherButtonTitles:nil, nil]; [alertNoconnection show]; } } but when I tried to send it gives me the following Exception: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFString appendString:]: nil argument' and it highlighted this line in SKPSMTPMessage.m [message appendString:[part objectForKey:kSKPSMTPPartMessageKey]]; and I Can't understand what is nil exactly Can Anyone help me in this issue? Thanks in Advance.

    Read the article

  • Parsing json in ios

    - by gaps
    i have the follwing json string ,can anybody tell me how to get the value of role_name {"response":"success","user":{"created_at":"2011-11-16T05:48:31Z","ud_id":"1234567890","last_sign_in_ip":"182.72.141.194","updated_at":"2011-11-19T08:58:27Z","account_id":21,"last_name":"dfg","role_name":"Parent","email":"[email protected]","first_name":"abc"},"status":"200"} code for parsing is NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSLog(@"resp--- %@",responseString); NSArray* latestLoans = [(NSDictionary*)[responseString JSONValue] objectForKey:@"user"]; NSDictionary* loan = [latestLoans objectAtIndex:0]; NSString* name = [loan objectForKey:@"last_name"];

    Read the article

  • Correcting a plist with dictionaries

    - by ingenspor
    Plist is copyed to documents directory if it doesn't exist. If it already exists, I want to use the "Name" key from NSDictionary in bundleArray to find the matching NSDictionary in documentsArray. When the match is found, I want to check for changes in the strings and replace them if there is a change. If a match is not found it means this dictionary must be added to documents plist. This is my code: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self managePlist]; return YES; } - (void)managePlist { NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Objects.plist"]; NSString *bundle = [[NSBundle mainBundle] pathForResource:@"Objects" ofType:@"plist"]; NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath: path]) { [fileManager copyItemAtPath:bundle toPath:path error:&error]; } else { NSArray *bundleArray = [[NSArray alloc] initWithContentsOfFile:bundle]; NSMutableArray *documentArray = [[NSMutableArray alloc] initWithContentsOfFile:path]; BOOL updateDictionary = NO; for(int i=0;i<bundleArray.count;i++) { NSDictionary *bundleDict=[bundleArray objectAtIndex:i]; BOOL matchInDocuments = NO; for(int ii=0;ii<documentArray.count;ii++) { NSMutableDictionary *documentDict = [documentArray objectAtIndex:ii]; NSString *bundleObjectName = [bundleDict valueForKey:@"Name"]; NSString *documentsObjectName = [documentDict valueForKey:@"Name"]; NSRange range = [documentsObjectName rangeOfString:bundleObjectName options:NSCaseInsensitiveSearch]; if (range.location != NSNotFound) { matchInDocuments = YES; } if (matchInDocuments) { if ([bundleDict objectForKey:@"District"] != [documentDict objectForKey:@"District"]) { [documentDict setObject:[bundleDict objectForKey:@"District"] forKey:@"District"]; updateDictionary=YES; } } else { [documentArray addObject:bundleDict]; updateDictionary=YES; } } } if(updateDictionary){ [documentArray writeToFile:path atomically:YES]; } } } If I run my app now I get this message: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object' How can I fix this? When this is fixed, do you think my code will work? If not, I would be happy for some suggestions on how to do this. I have struggled for a while and really need to publish the update with the corrections! Thanks a lot for your help.

    Read the article

  • What kind of structure should I use to keep prospectus of a medicine?

    - by ahmet732
    My project is similar to: Users search the name of a medicine from a table. Then touch the medicine he/she looked for . Then prospectus of that medicine will appear on the view... How should I keep prospectus of medicine?(prospectus of a medicine consists of several lines of text) SQLite or NSDictionary thing... I thought that NSDictionary will not go well with my need... Any answers ???

    Read the article

  • Get nested data from local JSON file

    - by Lbase
    Now that I have the NSDictionary object JSONDictionary, how do I get the nested data inside of it? NSString *JSONFilePath = [[NSBundle mainBundle] pathForResource:@"sAPI" ofType:@"json"]; NSData *JSONData = [NSData dataWithContentsOfFile:JSONFilePath]; NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil]; NSLog(@"Dictionary: %@", JSONDictionary); sAPI.json snippet: { "ss": [{ "name": "bl", }, "ls": [{ "name": "ML", "abbreviation": "ml", "id": 10,

    Read the article

  • Cannot read values from [NSUserDefaults standardUserDefaults] after synchronize

    - by Nonlinearsound
    In the Application Delegate didFinishLaunching method, I am using the following code to build up a new NSDictionary to be used as the new settings bundle for the user: NSNumber *testValue = (NSNumber*)[[NSUserDefaults standardUserDefaults] objectForKey:@"settingsversion"]; if (testValue == nil) { NSNumber *numNewDB = [NSNumber numberWithBool:NO]; NSNumber *numFirstUse = [NSNumber numberWithBool:YES]; NSDate *dateLastStatic = [NSDate date]; NSDate *dateLastMobile = [NSDate date]; NSNumber *numSettingsversion = [NSNumber numberWithFloat:1.0]; NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys: numNewDB, @"newdb", numFirstUse, @"firstuse", numSettingsversion, @"settingsversion", dateLastStatic, @"laststaticupdate", dateLastMobile, @"lastmobileupdate", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults]; [[NSUserDefaults standardUserDefaults] synchronize]; } Later in another ViewController I am trying to read back a value from that same Dictionary, saved as the NSUserDefaults - well at least I thought it would, but I don't get any valid object pointer for the desired member lastUpdate back there: in .h file: NSDate *lastUpdate; in the .m file in a member function: lastUpdate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"laststaticupdate"]; Even, if I print out the content of [NSUserDefaults standardUserDefaults] I only get this: 2010-04-29 15:13:22.322 myApp[4136:207] Content of UserDefaults: <NSUserDefaults: 0x11d340> This leads me to the conclusion that there is no standardUserDefaults dictionary somewhere in memory or it cannot be determined as such a structure. Edit: Every time, I restart the app ión the device, the check for testValue is Nil and I am building up the dictionary again but after one run it should be persistent on the Phone, right? Am I doing something wrong somewhere in between? I have the feeling that I yet didn't really understand how to load and save settings persistent for a certain application on the iPhone. Is there anything I have to do additionally to this? Integrating a settings.bundle in XCode or saving the dictionary manually to the Documents folder? Can someone help me out here? Thanks a lot!

    Read the article

  • retrieve my wall post in my native i phone application

    - by hardik
    hello all i want to retrieve my all the wall post that i have posted until now i am using this fql query from my native iphone application in order to fetch it but i think i am maiking some mistake please guide me how could i do that the following is my fql query to get wall post - (void)session:(FBSession*)session didLogin:(FBUID)uid { NSString *fql = [NSString stringWithFormat:@"SELECT comments, likes FROM stream WHERE post_id=100000182297319"]; NSLog(@"session key is %@",_session.sessionKey); NSLog(@"from global key is %@",[twitfacedemoAppDelegate getfacebookkey]); NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"]; [[FBRequest requestWithDelegate:self] call:@"facebook.fql.query" params:params]; this is my other delgate method to get the wall post but this code is not working - (void)request:(FBRequest*)request didLoad:(id)result { @try { NSLog(@"result is %@",result); if(result==nil) { UIAlertView *a=[[UIAlertView alloc]initWithTitle:@"Can't login" message:@"You cant login here." delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil]; [a show]; [a release]; } else { NSArray* users = result; NSDictionary* user = [users objectAtIndex:0]; NSString* name = [[NSString alloc]initWithString:[user objectForKey:@"name"]]; NSLog(@"name is %@",name); _label.text = [NSString stringWithFormat:@"Logged in as %@", name]; NSString *globalfacebookname; globalfacebookname=[[NSString alloc]initWithString:name]; NSLog(@"value is %@",globalfacebookname); NSString *fid=[user objectForKey:@"uid"]; NSLog(@"FACEBOOK ID WITH STRING DATATYP %@",fid); [twitfacedemoAppDelegate fetchfacebookid:fid]; } } @catch (NSException * e) { NSLog(@"Problem in dialog didFailWithError:%@",e); } } please guide me how could i retrieve my all the post from facebook to my native iphone application through fql query thanks in advance

    Read the article

  • Using the Apple Scripting bridge with Mail to send an attachment causes the message background to go

    - by Naym
    Hello, When I use the Apple Scripting Bridge to send a message with an attachment the background of the message is set to black which is a problem because the text is also black. The code in question is: MailApplication *mail = [SBApplication applicationWithBundleIdentifier:@"com.apple.Mail"]; /* create a new outgoing message object */ MailOutgoingMessage *emailMessage = [[[mail classForScriptingClass:@"outgoing message"] alloc] initWithProperties: [NSDictionary dictionaryWithObjectsAndKeys: emailSubject, @"subject", [self composeEmailBody], @"content", nil]]; /* add the object to the mail app */ [[mail outgoingMessages] addObject: emailMessage]; /* set the sender, show the message */ emailMessage.sender = [NSString stringWithFormat:@"%@ <%@>",[[[mail accounts] objectAtIndex:playerOptions.mailAccount] fullName],[[[[mail accounts] objectAtIndex:playerOptions.mailAccount] emailAddresses] objectAtIndex:0]]; emailMessage.visible = YES; /* create a new recipient and add it to the recipients list */ MailToRecipient *theRecipient = [[[mail classForScriptingClass:@"to recipient"] alloc] initWithProperties: [NSDictionary dictionaryWithObjectsAndKeys: opponentEmail, @"address", nil]]; [emailMessage.toRecipients addObject: theRecipient]; /* add an attachment, if one was specified */ if ( [playerInfo.gameFile length] > 0 ) { /* create an attachment object */ MailAttachment *theAttachment = [[[mail classForScriptingClass:@"attachment"] alloc] initWithProperties: [NSDictionary dictionaryWithObjectsAndKeys: playerInfo.gameFile, @"fileName", nil]]; /* add it to the list of attachments */ [[emailMessage.content attachments] addObject: theAttachment]; } /* send the message */ [emailMessage send]; The actual change to the background colour occurs on the second last line, which is: [[emailMessage.content attachments] addObject: theAttachment]; The code sections above are essentially lifted from the SBSendMail example code from Apple. At this stage I've really only made the changes necessary to integrate with the data from my application. If I build and run the SBSendMail example after freshly downloading it from Apple the message background is also changed to black with execution of the same line. It does not appear to matter which type of file is attached, where it is located, or on which computer or operating system is used. This could be a bug in Apple's scripting bridge but has anyone come across this problem and found a solution? ALternatively does anyone know if the background colour of a MailOutgoingMessage instance can be changed with the scripting bridge? Thanks for any assistance with this, Naym.

    Read the article

  • Singleton EXC_BAD_ACCESS

    - by lclaud
    Hi, so I have a class that I decleare as a singleton and in that class I have a NSMutableArray that contains some NSDictionaries with some key/value pairs in them. The trouble is it doesn't work and I dont't know why... I mean it crashes with EXC_BAD_ACCESS but i don't know where. I followed the code and it did create a new array on first add, made it to the end of the funtion ..and crashed ... @interface dataBase : NSObject { NSMutableArray *inregistrari; } @property (nonatomic,retain) NSMutableArray *inregistrari; -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu; -(NSDictionary *)raportIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)luniDisponibileIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)aniDisponibiliIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)vectorDateIntreData:(NSDate *)dataI siData:(NSDate *)dataF; -(void)salveazaInFisier; -(void)incarcaDinFisier; + (dataBase *)shareddataBase; @end And here is the .m file #import "dataBase.h" #import "SynthesizeSingleton.h" @implementation dataBase @synthesize inregistrari; SYNTHESIZE_SINGLETON_FOR_CLASS(dataBase); -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu{ NSNumber *v=[NSNumber numberWithBool:venit]; NSArray *input=[NSArray arrayWithObjects:data,suma,v,detaliu,nil]; NSArray *keys=[NSArray arrayWithObjects:@"data",@"suma",@"venit",@"detaliu",nil]; NSDictionary *inreg=[NSDictionary dictionaryWithObjects:input forKeys:keys]; if(inregistrari == nil) { inregistrari=[[NSMutableArray alloc ] initWithObjects:inreg,nil]; }else { [inregistrari addObject:inreg]; } [inreg release]; [input release]; [keys release]; } It made it to the end of that adaugaInregistrareCuData ... ok . said the array had one object ... and then crashed

    Read the article

  • Why is my UIWebView not scrollable?

    - by Thomas
    In my most frustrating roadblock to date, I've come across a UIWebView that will NOT scroll! I call it via this IBAction: -(IBAction)session2ButtonPressed:(id)sender { Session2ViewController *session2View = [[Session2ViewController alloc]initWithNibName:@"Session2ViewController" bundle:nil]; self.addictionViewController = session2View; [self.view insertSubview:addictionViewController.view atIndex:[self.view.subviews count]]; [session2View release]; } In the viewDidLoad of Session2ViewController.m, I have - (void)viewDidLoad { [super viewDidLoad]; // TRP - Grab data from plist // TRP - Build file path to the plist NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Addiction" ofType:@"plist"]; // TRP - Create NSDictionary with contents of the plist NSDictionary *addictionDict = [NSDictionary dictionaryWithContentsOfFile:filePath]; // TRP - Create an array with contents of the dictionary NSArray *addictionData = [addictionDict objectForKey:@"Addiction1"]; NSLog(@"addictionData (array): %@", addictionData); // TRP - Create a string with the contents of the array NSString *addictionText = [NSString stringWithFormat:@"<DIV style='font-family:%@;font-size:%d;'>%@</DIV>", @"Helvetica", 18, [addictionData objectAtIndex:1]]; addictionInfo.backgroundColor = [UIColor clearColor]; // TRP - Load the string created and stored into addictionText and display in the UIWebView [addictionInfo loadHTMLString:addictionText baseURL:nil]; // TODO: MAKE THIS WEBVIEW SCROLL!!!!!! } In the nib, I connected my web view to the delegate and to the outlet. When I run my main project, the plist with my HTML code shows up, but does not scroll. I copied and pasted this code into a new project, wired the nib the exact same way, and badda-boom badda-bing. . . it works. I even tried to create a new nib from scratch in this project, and the exact same code would not work. Whiskey Tango Foxtrot Any ideas?? Thanks! Thomas

    Read the article

  • sigleton EXC_BAD_ACCESS

    - by lclaud
    Hi, so I have a class that I decleare as a singleton and in that class I have a NSMutableArray that contains some NSDictionaries with some key/value pairs in them. The trouble is it doesn't work and I dont't know why... I mean it crashes with EXC_BAD_ACCESS but i don't know where. I followed the code and it did create a new array on first add, made it to the end of the funtion ..and crashed ... @interface dataBase : NSObject { NSMutableArray *inregistrari; } @property (nonatomic,retain) NSMutableArray *inregistrari; -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu; -(NSDictionary *)raportIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)luniDisponibileIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)aniDisponibiliIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)vectorDateIntreData:(NSDate *)dataI siData:(NSDate *)dataF; -(void)salveazaInFisier; -(void)incarcaDinFisier; + (dataBase *)shareddataBase; @end And here is the .m file #import "dataBase.h" #import "SynthesizeSingleton.h" @implementation dataBase @synthesize inregistrari; SYNTHESIZE_SINGLETON_FOR_CLASS(dataBase); -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu{ NSNumber *v=[NSNumber numberWithBool:venit]; NSArray *input=[NSArray arrayWithObjects:data,suma,v,detaliu,nil]; NSArray *keys=[NSArray arrayWithObjects:@"data",@"suma",@"venit",@"detaliu",nil]; NSDictionary *inreg=[NSDictionary dictionaryWithObjects:input forKeys:keys]; if(inregistrari == nil) { inregistrari=[[NSMutableArray alloc ] initWithObjects:inreg,nil]; }else { [inregistrari addObject:inreg]; } [inreg release]; [input release]; [keys release]; } It made it to the end of that adaugaInregistrareCuData ... ok . said the array had one object ... and then crashed

    Read the article

  • EXC_BAD_ACCESS with NSUserdefaults on iphone.

    - by Andreas Johannessen
    I have the following code in my ApplicationDelegate. My deployment target is 3.0 and upwards, however I get a EXC_BAD_ACCESS when I launch the app with the following code on my iPhone with 3.1.3, however on the simulator which has 4.2 it runs fine. I would really appriciate help on this one, thanks in advance. When I comment this block when I deploy to 3.1.3 device it runs without bad access. + (void)initialize { NSString *path = [[NSBundle mainBundle] bundlePath]; NSString *pListPath = [path stringByAppendingPathComponent:@"Settings.bundle/Root.plist"]; NSDictionary *pList = [NSDictionary dictionaryWithContentsOfFile:pListPath]; NSMutableArray *prefsArray = [pList objectForKey:@"PreferenceSpecifiers"]; NSMutableDictionary *regDictionary = [NSMutableDictionary dictionary]; for (NSDictionary *dict in prefsArray) { NSString *key = [dict objectForKey:@"Key"]; if(key) { id value = [dict objectForKey:@"DefaultValue"]; [regDictionary setObject:value forKey:key]; } } [[NSUserDefaults standardUserDefaults] registerDefaults:regDictionary]; } UPDATE: I traced the error to happen on this line: [[NSUserDefaults standardUserDefaults] registerDefaults:regDictionary]; So there is probaly another syntax on earlier iOS, or am I wrong?

    Read the article

  • Instance of method leaking, iPhone

    - by Wolfert
    The following method shows up as leaking while performing a memory-leaks test with Instruments: - (NSDictionary*) initSigTrkLstWithNiv:(int)pm_SigTrkNiv SigTrkSig:(int)pm_SigTrkSig SigResIdt:(int)pm_SigResIdt SigResVal:(int)pm_SigResVal { NSArray *objectArray; NSArray *keyArray; if (self = [super init]) { self.SigTrkNiv = [NSNumber numberWithInt:pm_SigTrkNiv]; self.SigTrkSig = [NSNumber numberWithInt:pm_SigTrkSig]; self.SigResIdt = [NSNumber numberWithInt:pm_SigResIdt]; self.SigResVal = [NSNumber numberWithInt:pm_SigResVal]; objectArray = [NSArray arrayWithObjects:SigTrkNiv,SigTrkSig,SigResIdt,SigResVal, nil]; keyArray = [NSArray arrayWithObjects:@"SigTrkNiv", @"SigTrkSig", @"SigResIdt", @"SigResVal", nil]; self = [NSDictionary dictionaryWithObjects:objectArray forKeys:keyArray]; } return self; } code that invokes the instance: NSDictionary *lv_SigTrkLst = [[SigTrkLst alloc]initSigTrkLstWithNiv:[[tempDict objectForKey:@"SigTrkNiv"] intValue] SigTrkSig:[[tempDict objectForKey:@"SigTrkSig"] intValue] SigResIdt:[[tempDict objectForKey:@"SigResIdt"] intValue] SigResVal:[[tempDict objectForKey:@"SigResVal"] intValue]]; [[QBDataContainer sharedDataContainer].SigTrkLstArray addObject:lv_SigTrkLst]; [lv_SigTrkLst release]; Instruments informs that 'SigTrkLst' is leaking. Even though I have released the instance? (I know that adding it to the array increments the retainCount by 1 but releasing it twice removes it from the array?)

    Read the article

  • help me to parse JSON value using JSONTouch

    - by EquinoX
    I have the following json: http://www.adityaherlambang.me/webservice.php?user=2&num=10&format=json I would like to get all the name in this data by the following code, but it gives an error. How can I fix it? NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSDictionary *results = [responseString JSONValue]; NSDictionary *users = [results objectForKey:@"users"] objectForKey:@"user"]; for (NSDictionary *user in users){ //NSLog(@"key:%@, value:%@", user, [user objectForKey:user]); NSString *title = [users objectForKey:@"NAME"]; NSLog(@"%@", title); } Error: 2011-01-29 00:18:50.386 NeighborMe[7763:207] -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0xb618840 2011-01-29 00:18:50.388 NeighborMe[7763:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0xb618840' *** Call stack at first throw: ( 0 CoreFoundation 0x027d9b99 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x0292940e objc_exception_throw + 47 2 CoreFoundation 0x027db6ab -[NSObject(NSObject) doesNotRecognizeSelector:] + 187 3 CoreFoundation 0x0274b2b6 ___forwarding___ + 966 4 CoreFoundation 0x0274ae72 _CF_forwarding_prep_0 + 50 5 NeighborMe 0x0000bd75 -[NeighborListViewController connectionDidFinishLoading:] + 226 6 Foundation 0x0007cb96 -[NSURLConnection(NSURLConnectionReallyInternal) sendDidFinishLoading] + 108 7 Foundation 0x0007caef _NSURLConnectionDidFinishLoading + 133 8 CFNetwork 0x02d8d72f _ZN19URLConnectionClient23_clientDidFinishLoadingEPNS_26ClientConnectionEventQueueE + 285 9 CFNetwork 0x02e58fcf _ZN19URLConnectionClient26ClientConnectionEventQueue33processAllEventsAndConsumePayloadEP20XConnectionEventInfoI12XClientEvent18XClientEventParamsEl + 389 10 CFNetwork 0x02e5944b _ZN19URLConnectionClient26ClientConnectionEventQueue33processAllEventsAndConsumePayloadEP20XConnectionEventInfoI12XClientEvent18XClientEventParamsEl + 1537 11 CFNetwork 0x02d82968 _ZN19URLConnectionClient13processEventsEv + 100 12 CFNetwork 0x02d827e5 _ZN17MultiplexerSource7performEv + 251 13 CoreFoundation 0x027bafaf __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15 14 CoreFoundation 0x0271939b __CFRunLoopDoSources0 + 571 15 CoreFoundation 0x02718896 __CFRunLoopRun + 470 16 CoreFoundation 0x02718350 CFRunLoopRunSpecific + 208 17 CoreFoundation 0x02718271 CFRunLoopRunInMode + 97 18 GraphicsServices 0x030b800c GSEventRunModal + 217 19 GraphicsServices 0x030b80d1 GSEventRun + 115 20 UIKit 0x002e9af2 UIApplicationMain + 1160 21 NeighborMe 0x00001c34 main + 102 22 NeighborMe 0x00001bc5 start + 53 23 ??? 0x00000001 0x0 + 1 ) terminate called after throwing an instance of 'NSException' I really just wanted to be able to iterate through the names

    Read the article

  • Save many-to-one relationship from JSON into Core Data

    - by Snow Crash
    I'm wanting to save a Many-to-one relationship parsed from JSON into Core Data. The code that parses the JSON and does the insert into Core Data looks like this: for (NSDictionary *thisRecipe in recipes) { Recipe *recipe = [NSEntityDescription insertNewObjectForEntityForName:@"Recipe" inManagedObjectContext:insertionContext]; recipe.title = [thisRecipe objectForKey:@"Title"]; NSDictionary *ingredientsForRecipe = [thisRecipe objectForKey:@"Ingredients"]; NSArray *ingredientsArray = [ingredientsForRecipe objectForKey:@"Results"]; for (NSDictionary *thisIngredient in ingredientsArray) { Ingredient *ingredient = [NSEntityDescription insertNewObjectForEntityForName:@"Ingredient" inManagedObjectContext:insertionContext]; ingredient.name = [thisIngredient objectForKey:@"Name"]; } } NSSet *ingredientsSet = [NSSet ingredientsArray]; [recipe setIngredients:ingredientsSet]; Notes: "setIngredients" is a Core Data generated accessor method. There is a many-to-one relationship between Ingredients and Recipe However, when I run this I get the following error: NSCFDictionary managedObjectContext]: unrecognized selector sent to instance If I remove the last line (i.e. [recipe setIngredients:ingredientsSet];) then, taking a peek at the SQLite database, I see the Recipe and Ingredients have been stored but no relationship has been created between Recipe and Ingredients Any suggestions as to how to ensure the relationship is stored correctly?

    Read the article

  • iPhone SDK / Objective C Syntax Question

    - by Koppo
    To all, I was looking at the sample project from http://iphoneonrails.com/ and I saw they took the NSObject class and added methods to it for the SOAP calls. Their sample project can be downloaded from here http://iphoneonrails.com/downloads/objective_resource-1.01.zip. My question is related to my lack of knowledge on the following syntax as I haven't seen it yet in a iPhone project. There is a header file called NSObject+ObjectiveResource.h where they declare and change NSObject to have extra methods for this project. Is the "+ObjectiveResource.h" in the name there a special syntax or is that just the naming convention of the developers. Finally inside the class NSObject we have the following #import <Foundation/Foundation.h> @interface NSObject (ObjectiveResource) // Response Formats typedef enum { XmlResponse = 0, JSONResponse, } ORSResponseFormat; // Resource configuration + (NSString *)getRemoteSite; + (void)setRemoteSite:(NSString*)siteURL; + (NSString *)getRemoteUser; + (void)setRemoteUser:(NSString *)user; + (NSString *)getRemotePassword; + (void)setRemotePassword:(NSString *)password; + (SEL)getRemoteParseDataMethod; + (void)setRemoteParseDataMethod:(SEL)parseMethod; + (SEL) getRemoteSerializeMethod; + (void) setRemoteSerializeMethod:(SEL)serializeMethod; + (NSString *)getRemoteProtocolExtension; + (void)setRemoteProtocolExtension:(NSString *)protocolExtension; + (void)setRemoteResponseType:(ORSResponseFormat) format; + (ORSResponseFormat)getRemoteResponseType; // Finders + (NSArray *)findAllRemote; + (NSArray *)findAllRemoteWithResponse:(NSError **)aError; + (id)findRemote:(NSString *)elementId; + (id)findRemote:(NSString *)elementId withResponse:(NSError **)aError; // URL construction accessors + (NSString *)getRemoteElementName; + (NSString *)getRemoteCollectionName; + (NSString *)getRemoteElementPath:(NSString *)elementId; + (NSString *)getRemoteCollectionPath; + (NSString *)getRemoteCollectionPathWithParameters:(NSDictionary *)parameters; + (NSString *)populateRemotePath:(NSString *)path withParameters:(NSDictionary *)parameters; // Instance-specific methods - (id)getRemoteId; - (void)setRemoteId:(id)orsId; - (NSString *)getRemoteClassIdName; - (BOOL)createRemote; - (BOOL)createRemoteWithResponse:(NSError **)aError; - (BOOL)createRemoteWithParameters:(NSDictionary *)parameters; - (BOOL)createRemoteWithParameters:(NSDictionary *)parameters andResponse:(NSError **)aError; - (BOOL)destroyRemote; - (BOOL)destroyRemoteWithResponse:(NSError **)aError; - (BOOL)updateRemote; - (BOOL)updateRemoteWithResponse:(NSError **)aError; - (BOOL)saveRemote; - (BOOL)saveRemoteWithResponse:(NSError **)aError; - (BOOL)createRemoteAtPath:(NSString *)path withResponse:(NSError **)aError; - (BOOL)updateRemoteAtPath:(NSString *)path withResponse:(NSError **)aError; - (BOOL)destroyRemoteAtPath:(NSString *)path withResponse:(NSError **)aError; // Instance helpers for getting at commonly used class-level values - (NSString *)getRemoteCollectionPath; - (NSString *)convertToRemoteExpectedType; //Equality test for remote enabled objects based on class name and remote id - (BOOL)isEqualToRemote:(id)anObject; - (NSUInteger)hashForRemote; @end What is the "ObjectiveResource" in the () mean for NSObject? What is that telling Xcode and the compiler about what is happening..? After that things look normal to me as they have various static and instance methods. I know that by doing this all user classes that inherit from NSObject now have all the extra methods for this project. My question is what is the parenthesis are doing after the NSObject. Is that referencing a header file, or is that letting the compiler know that this class is being over ridden. Thanks again and my apologies ahead of time if this is a dumb question but just trying to learn what I lack.

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >