Dynamic Table view data source - iphone

Hi I am doing a app in which i use a Dynamic view table, Bit i have a problem with NSManged Objects, can any one find out whats going wrong.
find the code below for your reference.
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return ([self.controlSelections count]);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"plainCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
id controlOption = [self.controlSelections objectAtIndex:indexPath.row];
NSString *option = nil;
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if ([controlOption isKindOfClass:[NSString class]])
{
option = (NSString *)controlOption;
cell.textLabel.text = option;
}
else if ([controlOption isKindOfClass:[NSDictionary class]])
{
NSDictionary *optionDict = (NSDictionary *)controlOption;
option = [optionDict valueForKey:self.listKey];
cell.textLabel.text = option;
}
else if ([controlOption isKindOfClass:[NSManagedObject class]])
{
NSManagedObject *context=[self NSManagedObject];
NSManagedObject *optionData = (NSManagedObject *)controlOption;
option = [optionData valueForKey:self.listKey];
cell.textLabel.text = option;
}
return cell;
}
the problem is in the following code it is not taking NSMangedObject:
else if ([controlOption isKindOfClass:[NSManagedObject class]])
{
NSManagedObject *context=[self NSManagedObject];
NSManagedObject *optionData = (NSManagedObject *)controlOption;
option = [optionData valueForKey:self.listKey];
cell.textLabel.text = option;
}
any help will be appreciated. thanks in advance.

import in Prefix.pch file

Try something on these lines -
else if ([controlOption isKindOfClass:[NSManagedObject class]])
{
NSManagedObjectContext *context=[self managedObjectContext]; //I guess you have MOC somewhere.
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:[optionData valueForKey:self.listKey] inManagedObjectContext: context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
cell.textLabel.text = [objects objectAtIndex:0]; //for eg
}

Related

To display correct value of NSManagerObject on cell.textLabel.text

I am newbie with Xcode 5 and start do some coding with appcode.com's tutorial.
I can't get the the proper search result printing back to tableview(core data), any suggestion will be highly appreciated, thanks in advance! cheers.
#import "RecipeStoreTableViewController.h"
#import "AddRecipeViewController.h"
#interface RecipeStoreTableViewController () {
NSMutableArray *recipes;
NSArray *searchResults;
}
#end
#implementation RecipeStoreTableViewController
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the recipes from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Recipe"];
recipes = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
// NSLog(#"test %#", [recipes valueForKey:#"name"]);
// Reload table data
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
}else{
return [recipes count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *recipe = [recipes objectAtIndex:indexPath.row];
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults valueForKey:#"name"];
NSString *description = [[NSString alloc] initWithFormat:#"%# - %#", [searchResults valueForKey:#"image"], [searchResults valueForKey:#"prepTime"]];
cell.detailTextLabel.text = description;
}else{
cell.textLabel.text = [recipe valueForKey:#"name"];
NSString *description = [[NSString alloc] initWithFormat:#"%# - %#", [recipe valueForKey:#"image"], [recipe valueForKey:#"prepTime"]];
cell.detailTextLabel.text = description;
}
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [self managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete object from database
[context deleteObject:[recipes objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't Delete! %# %#", error, [error localizedDescription]);
return;
}
// Remove recipe from table view
[recipes removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"UpdateRecipe"]) {
NSManagedObject *selectedRecipe = [recipes objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
UINavigationController *destViewController = segue.destinationViewController;
AddRecipeViewController *recipeViewController = (AddRecipeViewController*)destViewController.topViewController;
recipeViewController.recipe = selectedRecipe;
}
}
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"name contains[c] %#", searchText];
searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
#end
You are calling the valueForKey on NSMutableArray object, which should be called on NSManagedObject
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *recipe;
if (tableView == self.searchDisplayController.searchResultsTableView)
recipe = searchResults[indexPath.row];
else
recipe = recipes[indexPath.row];
cell.textLabel.text = [recipe valueForKey:#"name"];
NSString *description = [[NSString alloc] initWithFormat:#"%# - %#", [recipe valueForKey:#"image"], [recipe valueForKey:#"prepTime"]];
cell.detailTextLabel.text = description;
return cell;
}

core data search issue iOS 5

Using core data, data is being fetched properly and shown properly, issue is with the search that it does not filter the results, whatever I type in the search bar, it does show the same table view with same data in the filtered results..
- (void)viewDidLoad
{
[super viewDidLoad];
if (context == nil)
{
context = [(VektorAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
app = [[UIApplication sharedApplication] delegate];
[self getData];
// create a filtered list that will contain products for the search results table.
filteredListItems = [[NSMutableArray alloc] initWithCapacity:[self.plateNumbers count]];
// restore search settings if they were saved in didReceiveMemoryWarning.
if (self.savedSearchTerm){
[self.searchDisplayController setActive:self.searchWasActive];
[self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
[self.searchDisplayController.searchBar setText:savedSearchTerm];
self.savedSearchTerm = nil;
}
}
Fetching data from core data:
-(void)getData {
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Favouritesdata" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setFetchBatchSize:20];
[request setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"licenseplate" ascending:NO];
NSArray *newArray = [[NSArray alloc]initWithObjects:sort, nil];
[request setSortDescriptors:newArray];
NSLog(#"newArray: %#", newArray);
NSError *error;
results = [[context executeFetchRequest:request error:&error] mutableCopy];
plateNumbers = [results valueForKey:#"licenseplate"];
NSLog(#"plateNumbers: %#", plateNumbers);
[self setLicensePlateArray:results];
[self.favouritesTable reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == favouritesTable) {
return [licensePlateArray count];
} else { // handle search results table view
return [filteredListItems count];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == favouritesTable) {
cellValue = [licensePlateArray objectAtIndex:indexPath.row];
} else { // handle search results table view
cellValue = [filteredListItems objectAtIndex:indexPath.row];
}
static NSString *CellIdentifier = #"vlCell";
VehicleListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog(#"Cell Created");
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"VehicleListCell" owner:nil options:nil];
for (id currentObject in nibObjects) {
if ([currentObject isKindOfClass:[VehicleListCell class]]) {
cell = (VehicleListCell *)currentObject;
}
}
NSInteger cellVal = indexPath.row;
NSLog(#"indexPath.row: %i", cellVal);
UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(tableCellPressed:)];
pressRecongnizer.delegate = self;
pressRecongnizer.minimumPressDuration = 0.5f;
[cell addGestureRecognizer:pressRecongnizer];
[pressRecongnizer release];
}
cell.textLabel.font = [UIFont systemFontOfSize:10];
Favouritesdata *favdata = [results objectAtIndex:indexPath.row];
cell.licPlate.text = [favdata licenseplate];
NSLog(#"cellvalue for cellforRow: %#", cell.licPlate.text);
return cell;
}
Search bar implementation:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
self.filteredListItems = [self.plateNumbers filteredArrayUsingPredicate:resultPredicate];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
/* [self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
*/
if ([[searchString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length])
self.favouritesTable = controller.searchResultsTableView;
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
How to resolve this issue ?
Just make code clear before and define every methods, you are just setting predicate, not firing query for it.
just make separate method and just pass search text as parameter to that method for predicate and fire fetch query then reload table.

crashes in Xcode version 4.2 and iOS 5(released oct-12, 2011) at [self.tableview reload data]

i was implementing the table view programmatically, where i set property of mSelectedSubUnitIndex of (NSIndexPath) type as non atomic and retain and synthesized in .m . When i load my tableviewcontroller then method:
(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath
:(NSIndexPath *)indexPath
{
CGFloat height = 0.0;
SubUnit *subUnit = (SubUnit*)[mSubUnitsArray objectAtIndex:indexPath.row];
NSArray *subUnitExercises = [self sortArray:[subUnit.subUnitExercise allObjects]];
NSLog(#"mSelectedSubUnitIndex.row........%d",mSelectedSubUnitIndex.row);
NSLog(#"subUnitExercises........%d",[subUnitExercises count]);
if (indexPath.row == mSelectedSubUnitIndex.row && [subUnitExercises count]>1) {
height =CELL_EXPAND_HEIGHT ;
}
else {
height = CELL_NORMAL_HEIGHT;
}
return height;
}
run quite fine. When i return back to my tableviewcontoller from other controller then it crashes(object message send) at same method on line number 5 at NSLog, and give exception at method at [self.tableView reloadData];. It is resolved by commenting[self.tableView reloadData];.
-(void)viewDidAppear:(BOOL)animated
{
DebugLog(#"start");
//[self.tableview reloadData];
execountarray=[[NSMutableArray alloc]init];
for(int k=0;k<[mSubUnitsArray count];k++)
{
SubUnit *subUnit = (SubUnit*)[mSubUnitsArray objectAtIndex:k];
NSArray *subUnitExercises = [subUnit.subUnitExercise allObjects];
[execountarray addObject:[NSString stringWithFormat:#"%d",[subUnitExercises
count]]];
}
///////////////
if (managedObjectContext){
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"TSubUnitExerciseProgress" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
// Order the events by creation date, most recent first.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:#"editDate" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,
nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
[sortDescriptors release];
// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext
executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
myNotes = nil;
[myNotes removeAllObjects];
}
else
{
[myNotes setArray: mutableFetchResults];
}
//NSLog(#"My notes count:--------unitviewcontroller--------------->%d",
[myNotes count]);
if([myNotes count] ==0)
{
setExer1Done:NO;
setExer2Done:NO;
}
else
{
NSLog(#"hey :P");
}
}
// [self.tableview reloadData];
}
didSelectRowAtIndex
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath
{
DebugLog(#" -start- \n");
mSelectedSubUnitIndex = indexPath;
SubUnit *subUnit = (SubUnit*)[mSubUnitsArray objectAtIndex:indexPath.row];
NSArray *subUnitExercises = [self sortArray:[subUnit.subUnitExercise allObjects]];
if([subUnitExercises count]!=1)
{
NSArray* paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:
[mSelectedSubUnitIndex row] inSection:0]];
[tableview beginUpdates];
[tableview deleteRowsAtIndexPaths:paths
withRowAnimation:UITableViewRowAnimationFade];
[tableview insertRowsAtIndexPaths:paths
withRowAnimation:UITableViewRowAnimationFade];
[tableview endUpdates];
}
else
{
//SubUnit *subUnit = (SubUnit*)[mSubUnitsArray objectAtIndex:
[mSelectedSubUnitIndex row]];
SubUnit *subUnit = (SubUnit*)[mSubUnitsArray objectAtIndex:indexPath.row];
NSArray *subUnitExercises = [self sortArray:[subUnit.subUnitExercise
allObjects]];
if ([subUnitExercises count] > 0) {
SubUnitExercise *subUnitExercise = [subUnitExercises
objectAtIndex:0];
[self loadSubUnitExercise:subUnitExercise];
}
}
}
this is running on iOS 4 but when i build through Xcode version 4.2 and iOS 5 (released oct-12, 2011) then it crashes. Can't figure out the problem. help me out!!
cellForRowAtIndex method
now i am getting exception at if-statement at mSelectedsubunitindex.row when i scroll, but i resolved only checking that if (indexPath.row){}, and also row remain selected when i return bad to my tableview controller
- (void)tableView:(UITableView *)tableView willDisplayCell:
(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
DebugLog(#"-start- \n");
SubUnit *subUnit = (SubUnit*)[mSubUnitsArray objectAtIndex:indexPath.row];
NSArray *subUnitExercises = [self sortArray:[subUnit.subUnitExercise allObjects]];
NSString *str1 = [[subUnit performSelector:#selector(title)]copy];
if ([str1 isEqualToString:#"1. was/were"])
{
global = str1;
}
//if(indexPath.row==mSelectedSubUnitIndex.row)
if(indexPath.row)
{
if ([subUnitExercises count] != 1)
{
SubUnit *subUnit = (SubUnit*)[mSubUnitsArray objectAtIndex:
[mSelectedSubUnitIndex row]];
NSArray *subUnitExercises = [self sortArray:
[subUnit.subUnitExercise allObjects]];
SubUnitCell *subUnitcell = (SubUnitCell*) cell;
mCellSubTopicLabel.text = subUnit.title;
if([myNotes count] == 0)
{
NSNumber *isDone = [[subUnitExercises objectAtIndex:1] isDone];
[subUnitcell setExer2Done:NO];
mExer2Checkbox.image = [UIImage imageNamed:[isDone boolValue]?
kExerciseCheckmark :kExerciseWrongmark];
isDone = [[subUnitExercises objectAtIndex:0] isDone];
[subUnitcell setExer1Done:NO];
mExer1Checkbox.image = [UIImage imageNamed:[isDone boolValue]?
kExerciseCheckmark :kExerciseWrongmark];
}
else
{
NSNumber *isDone = [[subUnitExercises objectAtIndex:1] isDone];
[subUnitcell setExer2Done:[isDone boolValue]];
mExer2Checkbox.image = [UIImage imageNamed:[isDone boolValue]?
kExerciseCheckmark :kExerciseWrongmark];
isDone = [[subUnitExercises objectAtIndex:0] isDone];
[subUnitcell setExer1Done:[isDone boolValue]];
mExer1Checkbox.image = [UIImage imageNamed:[isDone boolValue]?
kExerciseCheckmark :kExerciseWrongmark];
}
[subUnitcell.contentView addSubview:mCellSubTopicContentView];
}
}
For some reason NSIndexPath assignment (=) and equality(==) is not working in IOS5. I have solved the problem using self before any NSIndexPath object e.g.
self.mSelectedSubUnitIndex
There is another way solving this assignment using copy like this:
anIndexPath = (NSIndexPath*) [anotherIndexPath copy];
Equality works in same way. Like:
if([self.mSelectedSubUnitIndex isEqual:anotherIndexPath])
{
}
Just had a quick once over of your code. Two things jump out at me:
1: The very last line of your tableView:cellForRowAtIndexPath: calls [self.tableview reloadData].
This is unnecessary as the returned cell will be displayed as you have just configured it. It would also seem that this would cause a drawing loop ("reloadData->cellForRowAtIndexPath->reloadData->cellForRowAtIndexPath-> etc..). Try removing this line and see if this fixes your problems.
2: You don't seem to be re-using cells although one of your comments seemt to imply that you think you are. I would expect the beginning of the method to start similar to the code below:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
/* Load a custom cell from a NIB
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];
cell = (UITableViewCell *)[nib objectAtIndex:0];
*/
// Assume SubUnitCell exists somewhere
SubUnitCell *cell = [[[SubUnitCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Retrieve config data and configure the cell as required in the code below - real config code needs to be added
NSNumber *isDone = [NSNumber numberWithBool:NO];
SubUnit *subUnit = (SubUnit*)[mSubUnitsArray objectAtIndex:[indexPath row]];
[cell setTitle:subUnit.title];
if([myNotes count] ==0)
{
[cell setExer1Done:NO];
[cell setExer2Done:NO];
}
else
{
NSLog(#"My notes count:--------unitviewcontroller----->%d",[myNotes count]);
}
// All your other configuration code
.......
.......
.......
return cell;
}
Also please try and post the symbolicated crash log so people can see the exact error and path to the error.

Add ability to set nil for a relationship core-data

I have two entity with a many-to-one relationship. For example Employee <<---> Shop. When I create a new employee, I can choose a shop for it. I fetch all the available shops and then I select one from the table view.
Now, I want to add a new row in this table to be able to set nil to the relationship, for example by adding a row called "None" and when it's selected, the relationship will be employee.shop = nil;
Is it possible? I don'w know how to configure the table view to do this job...
However, this is the code used to fetch the shops:
-(NSArray *)projectsList
{
if (!projectsList) {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Project" inManagedObjectContext:taskObject.managedObjectContext];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"title" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSArray *projects = [taskObject.managedObjectContext executeFetchRequest:request error:&error];
if (!projects) {
NSLog(#"Risultati della richiesta nulli!");
abort();
}
projectsList = [projects mutableCopy];
}
return projectsList;
}
and some tableView methods:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self projectsList] count];
}
- (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];
}
Project *project = (Project *)[[self projectsList] objectAtIndex:indexPath.row];
cell.textLabel.text = project.title;
if (project == taskObject.project) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
Project *project = (Project *)[projectsList objectAtIndex:indexPath.row];
taskObject.project = project;
NSError *error = nil;
if (![taskObject.managedObjectContext save:&error]) {
NSLog(#"Errore nel salvare il progetto per il task! %#, %#", error, [error userInfo]);
abort();
}
else {
[self.navigationController popViewControllerAnimated:YES];
}
}
Thank you so much!
This should do it.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self projectsList] count] + 1;
}
- (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];
}
if ( indexPath.row == [projectsList count] )
{
cell.textLabel.text = #"None";
cell.accessoryType = ( taskObject.project ) ? UITableViewCellAccessoryNone : UITableViewCellAccessoryCheckmark;
}
else
{
Project *project = (Project *)[[self projectsList] objectAtIndex:indexPath.row];
cell.textLabel.text = project.title;
if (project == taskObject.project) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
if ( indexPath.row == [projectsList count] )
{
taskObject.project = nil;
}
else
{
Project *project = (Project *)[projectsList objectAtIndex:indexPath.row];
taskObject.project = project;
}
NSError *error = nil;
if (![taskObject.managedObjectContext save:&error]) {
NSLog(#"Errore nel salvare il progetto per il task! %#, %#", error, [error userInfo]);
abort();
}
else {
[self.navigationController popViewControllerAnimated:YES];
}
}

Turning additional strings in this JSON array into a UITableView Detail

I have a NSURL request that brings back an array of "name" and "phone", "etc"... The "name" Key shows up fine on the master table, but I'm having trouble figuring out how to get the rest of the array to show up on the detail table when I select the row. (I have the DetailerTableViewController working to accept the view). Any help would be appreciated.
Thanks,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [rowsArray count];
NSLog(#"row count: %#",[rowsArray count]);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *dict = [rowsArray objectAtIndex: indexPath.row];
cell.textLabel.text = [dict objectForKey:#"name"];
cell.detailTextLabel.text = [dict objectForKey:#"loginName"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.0/255.0 green:207.0/255.0 blue:255.0/255.0 alpha:1.0];
self.title = NSLocalizedString(#"Master", #"Master");
NSURL *url = [NSURL URLWithString:#"http://10.0.1.8/~imac/iphone/jsontest.php"];
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
NSLog(jsonreturn); // Look at the console and you can see what the results are
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
// In "real" code you should surround this with try and catch
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
rowsArray = [dict objectForKey:#"member"];
[rowsArray retain];
}
NSLog(#"Array: %#",rowsArray);
NSLog(#"count is: %i", [self.rowsArray count]);
[jsonreturn release];
}
You need to implement:
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
to handle row selection and to push the view controller for the detail view.