Core Data Inverse RelationShip - iphone

I am creating Travel guide app using core data. I have 4 entities CITY ,RESTAURANTS ,
HOTEL AND FAMOUS PLACES. City is connected with all other entity because one city may have number of restaurants , hotels and places. City entity has 3 attribute Name ,Image ,Description. I am able to display list restaurants of selected city.In Restaurant Entity I have 4 attribute Name, Description ,Address and phone no..Now I want to show
this attribute detail of selected restaurant(of selected city) in next view.But how can I access restaurant description in next view..
Here is my code.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSMutableArray *restaurants = [[NSMutableArray alloc]initWithArray:[city.cityTorestaurants allObjects]];
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc]initWithKey:#"Name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:nameDescriptor,nil];
[restaurants sortUsingDescriptors:sortDescriptors];
[hotels sortUsingDescriptors:sortDescriptors];
[self setArrayOfRestaurants:restaurants];
[restaurants release];
[nameDescriptor release];
[sortDescriptors release];
[tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil ) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier]autorelease];
}
//set up cell
NSLog(#"For Restaurants List");
Restaurants *restaurants = [arrayOfRestaurants objectAtIndex:indexPath.row];
cell.textLabel.text = restaurants.Name;
return cell;
}
cityTorestaurants and restaurantTocity is relationship in core data..
Help Please..

In your RestaurantViewController create a property Restaurant* currentRestaurant
in your didSelectRowAtIndexPath:of the CityViewController set the property with self.restaurantVC.currentRestaurant = [arrayOfRestaurants objectAtIndex:indexPath.row];

Related

Sorted arrays doesn't delete what I want

I have a sorted NSMutableArray which works perfectly and all though when I try to delete an object it crashes the app then when I reload the app it didn't delete the right one.
I known that is due to the fact that this is now a sorted array because before I implemented this feature it worked fine though I haven't got a clue of how to fix it.
Here is the code I use to delete things from the array:
- (void) tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if ( editingStyle == UITableViewCellEditingStyleDelete ) {
Patient *thisPatient = [patients objectAtIndex:indexPath.row];
[patients removeObjectAtIndex:indexPath.row];
if (patients.count == 0) {
[super setEditing:NO animated:YES];
[self.tableView setEditing:NO animated:YES];
}
[self deletePatientFromDatabase:thisPatient.patientid];
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
}
It is being stopped at this line:
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
Here is the code that I use for sorting the array:
-(void) processForTableView:(NSMutableArray *)items {
for (Patient *thisPatient in items) {
NSString *firstCharacter = [thisPatient.patientName substringToIndex:1];
if (![charIndex containsObject:firstCharacter]) {
[charIndex addObject:firstCharacter];
[charCount setObject:[NSNumber numberWithInt:1] forKey:firstCharacter];
} else {
[charCount setObject:[NSNumber numberWithInt:[[charCount objectForKey:firstCharacter] intValue] + 1] forKey:firstCharacter];
}
}
charIndex = (NSMutableArray *) [charIndex sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
}
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:#"cell"];
NSString *letter = [charIndex objectAtIndex:[indexPath section]];
NSPredicate *search = [NSPredicate predicateWithFormat:#"patientName beginswith[cd] %#", letter];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"patientName" ascending:YES];
NSArray *filteredArray = [[patients filteredArrayUsingPredicate:search] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
if ( nil == cell ) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
NSLog(#"indexPath.row = %d, patients.count = %d", indexPath.row, patients.count);
Patient *thisPatient = [filteredArray objectAtIndex:[indexPath row]];
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", thisPatient.patientName, thisPatient.patientSurname];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.textColor = [UIColor blackColor];
if (self.editing) {
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
return cell;
}
I suspect this is quite a common thing that happens when you sort an array though it may not be.
Please say if you want any more code
It's not neccessarily because your array is sorted, but because the array you are populating your table from is not the same as the array that you are removing the object from.
Where are you sorting the patients array? Is the actual patients array being sorted or are you sorting it in your tableView delegates method and not actually sorting patients?
The reason for this is that the index of the object you deleted is not the same as the index that it has in the actual patients array (because one is sorted and one is not). Because of this, it is first deleting the wrong object, then it crashes because the tableView expects one to be deleted (so that it can animate that cell being removed) but the wrong one was deleted.

Order the tableview cell by the subtitle

i'm getting the distance of 2 points like this
[userLocation distanceFromLocation: annotationLocation] / 1000;
and setting this to the subtitle of a tableview like the image bellow
the question is, can i order this table by the distances (subtitle)?
Thanks!
and sorry for the bad english =x
You can order your UITableView's cells any way to want to, but you have to do it before showing them, when you create the table's data source. If you use an NSFetchResultsController, you can put the distance as the sort descriptor. And if you are using a simple NS(Mutable)Array, sort it before making it the table's source.
Like Chris said, you can do it with
NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:#"annotationLocation" ascending:YES];
If it is an NSArray what you are using, then:
[arrayOfObjects sortUsingDescriptors:[NSArray arrayWithObject:titleSorter];
and if it is an NSFetchResultsController:
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:titleSorter, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
Create an NSSortDescriptor to sort your rows:
NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:#"annotationLocation" ascending:YES];
[arrayOfObjects sortUsingDescriptors:[NSArray arrayWithObject:titleSorter];
Make an array with these distances, order it how you want and
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cellIdentifier";
UITableViewCell *_cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (_cell == nil) {
_cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
}
_cell.textLabel.text = #"Transcripts";
_cell.detailTextLabel.text = [yourArray objectAtIndex:indexPath.row];
return _cell;
}
well, something like that should do the trick.
Hope it helps
Assuming you have some certain objects holding a coordinate and put the objects in to an array locations, you can use a comparator block by doing:
locations = [locations sortedArrayUsingComparator: ^(id a, id b) {
CLLocationDistance dist_a= [[a objectsForKey:#"coordinate"] distanceFromLocation: userPosition];
CLLocationDistance dist_b= [[b objectsForKey:#"coordinate"] distanceFromLocation: userPosition];
if ( dist_a < dist_b ) {
return (NSComparisonResult)NSOrderedAscending;
} else if ( dist_a > dist_b) {
return (NSComparisonResult)NSOrderedDescending;
} else {
return (NSComparisonResult)NSOrderedSame;
}
}
You add this code to your viewWillAppear: to get updated locations each time you display the tableView.

Why am I seeing a crash when displaying this table view?

I am designing a simple navigation based application for EmployeeContactDirectory. I am displaying the list of Employee. For showing the list of employee, I am using the restfull webservice. I am getting proper response as I want. I have a utility class for Employee Data, class is EmployeeData.h and Employee.m (contains employeeId , employeeFirstName, employeeLastName). My code for parsing
// Code for parsing the response and getting desired field into the dictionary object and add the dictionaries into the array.
-(void)finishedReceivingData:(NSData *)data {
NSData *dataRes = [[restConnection stringData] dataUsingEncoding:NSUTF8StringEncoding];
////////////////Parsing with XPathQuery Start//////////////////////
if (dataRes != NULL) {
employeeData = [[EmployeeData alloc] init];
NSString *xPathQuery = [NSString stringWithFormat:#"/*",employeeData.employeeID];
NSArray *arrayWithObjectList = PerformXMLXPathQuery(dataRes, xPathQuery);
for(NSDictionary *childOfObjectList in arrayWithObjectList){
NSArray *arrayOfDataValueObj = (NSArray *)[childOfObjectList objectForKey:#"nodeChildArray"];
for(NSDictionary *childObjListDict in arrayOfDataValueObj){
NSArray *childObjListDataValue = (NSArray *)[childObjListDict objectForKey:#"nodeChildArray"];
for(NSDictionary *childDict in childObjListDataValue){
if([[childDict objectForKey:#"nodeName"] isEqualToString:#"FName" ])
{
employeeData.employeeFirstName = [childDict objectForKey:#"nodeContent"];
}
if([[childDict objectForKey:#"nodeName"] isEqualToString:#"EmpID"])
{
employeeData.employeeID = [childDict objectForKey:#"nodeContent"];
}
}
//employeeFirstNameArray = [NSArray arrayWithObjects:employeeData, nil];
employeeIDArray = [NSArray arrayWithObjects:employeeData, nil];
dictionaryEmployeeFirstName = [NSDictionary dictionaryWithObject:employeeData.employeeFirstName forKey:#"employeeData"];
dictionaryEmployeeID = [NSDictionary dictionaryWithObject:employeeData.employeeID forKey:#"employeeData"];
tempArray = [NSArray arrayWithObjects:dictionaryEmployeeFirstName, dictionaryEmployeeID, nil];
NSLog(#"size of temp %d",[tempArray count]);
}
}
//[employeeData release];
//employeeData = nil;
}
[self.tableviewEmloyeeList reloadData];
//////////////////////////////Parsing with XPathQuery end//////////
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell..
NSDictionary *dictionaryEmployee = [tempArray objectAtIndex:indexPath.row];
NSArray *firstNameArray = [dictionaryEmployee objectForKey:#"employeeData"];
NSString *cellValue = [firstNameArray objectAtIndex:indexPath.row];
NSLog(#"cellValue %#",cellValue);
cell.textLabel.text = cellValue;
return cell;
}
I am getting the message (Exc_bad_Access) when this line of code comes into the execution flow:
NSDictionary *dictionaryEmployee = [tempArray objectAtIndex:indexPath.row]
The EXC_Bad_Access is at the mail.m file at line nt retVal = UIApplicationMain(argc, argv, nil, nil);
So, Please tell me how can I set the data into the tableview when I am using NSDictionary. When, user clicks on the row of the tableview it will return the id of the selected employee.
Instead of the line
tempArray = [NSArray arrayWithObjects:dictionaryEmployeeFirstName, dictionaryEmployeeID, nil];
try the following,
if( tempArray )
{
[tempArray release];
tempArray = nil;
}
tempArray = [[NSArray arrayWithObjects:dictionaryEmployeeFirstName, dictionaryEmployeeID, nil] retain];
Since it is autoreleased, it might have been out of memory.
you need to implement a tableView delegate method called
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
here you will get the section & row clicked in the table

How to copy TableView cell data to a NSMutable Array?

Merged with How to copy TableView cell data to a NSMutable Array?.
I'm quite new to iphone development. I created To-Do List app using coredata.
I want to add all the names from "oneHero" manageObject to a NSMutable array (that means name1 to 1st index position of MutableArray , name2 to 2nd index position of Array)
this is my table view cellfor indexpath method
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *HeroTableViewCell = #"HeroTableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HeroTableViewCell];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:HeroTableViewCell] autorelease];
}
NSManagedObject *oneHero = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSInteger tab = [tabBar.items indexOfObject:tabBar.selectedItem];
switch (tab) {
case kByName:
cell.textLabel.text = [oneHero valueForKey:#"name"];
cell.detailTextLabel.text = [oneHero valueForKey:#"secretIdentity"];
break;
case kBySecretIdentity:
cell.detailTextLabel.text = [oneHero valueForKey:#"name"];
cell.textLabel.text = [oneHero valueForKey:#"secretIdentity"];
default:
break;
}
//listData = [[[NSMutableArray alloc] init]autorelease];
//if(indexPath.row==1){
//[listData addObject: [oneHero valueForKey:#"secretIdentity"]];
return cell;
}
Actually what I want to do is, retrieve all the names(those are location names) from my "oneHero" object and then show those locations in a mapView. That's why I want to copy those names in to seperate NSMutable array or just as Strings
Can you please give me a cording help . . .

Accessing elements from an array in objective c

I am trying to access individual elements of my array. This is an example of the contents of the array i am trying to access.
<City: 0x4b77fd0> (entity: Spot; id: 0x4b7e580 <x-coredata://D902D50B-C945-42E2-8F71-EDB62222C0A7/Spot/p5> ; data: {
CityToProvince = 0x4b7dbd0 <x-coredata://D902D50B-C945-42E2-8F71-EDB62222C0A7/County/p15>;
Description = "Friend";
Email = "bla#bla.com";
Age = 21;
Name = "Adam";
Phone = "+44175240";
}),
The elements i am trying to access are Name, Phone, etc ...
How would i go about doing this?
UPDATE:
OK, understanding that I am looking at core data now, how would I go about removing an object from being displayed in my table view?
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *object = (NSManagedObject *)[entityArray objectAtIndex:indexPath.row];
NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
return cell;
}
That doesn't look like an array. That looks like a Core Data entity. You may have an array of them, but it appears as though you're trying to access the members of the entity itself. To do so, you can use the NSManagedObject method -(id) valueForKey:.
NSManagedObject *entity = /* ... retrieve entity from Core Data ... */;
NSString *name = [entity valueForKey:#"Name"];