Tableview populated by a NSArray

Hi
Does anyone know of a good Tutorial to populate a NSTableView with a NSArray
Many thanks

Have you looked at the Apple sample code in TableViewSuite 1_SimpleTableView?

Similar Messages

  • Thumbnail view of a TableView populated by an ObservableList

    Hello,
    I'm populating a TableView dynamically with objects in an ObservableList.  I'd like to mark some rows with varying colors depending on their content and would like to display the marked rows in a thumbnail view of the TableView.  The idea is to basically do something like the awesome Beyond Compare app does in the top left side of their window (see http://www.scootersoftware.com/images/TextCompare.png). A click on the thumbnail would basically scroll your tableview to that location.  The square on the thumbnail represents what data is displayed on the screen and is sized proportionally with how long the TableView is and how many rows can be displayed on the screen at that time.
    Perhaps I can bind a ListView to the same ObservableList that's populating the TableView but just show an image (thin colored line) for each row of the TableView that has been marked.  Any ideas on how I could achieve something like this?
    Thanks

    In JavaFX8 you can get a filtered list from the ObservableList, and use that to populate the ListView (or whatever you decide to display). Just call table.getItems().filtered(...).
    In JavaFX 2.x, you can create an new ObservableList for your filtered data. Create a ListChangeListener and register it with table.getItems() and update your filtered data as necessary when the list changes. The tricky part is to update the filtered list when any relevant properties in the elements in the list change. For this you can create an observable list with an extractor.
    Here's an example. Note the way the observable list is created in the createData() method.
    import java.util.Arrays;
    import java.util.List;
    import javafx.application.Application;
    import javafx.beans.Observable;
    import javafx.beans.property.BooleanProperty;
    import javafx.beans.property.SimpleBooleanProperty;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.property.StringProperty;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.FXCollections;
    import javafx.collections.ListChangeListener;
    import javafx.collections.ObservableList;
    import javafx.scene.Scene;
    import javafx.scene.control.ListView;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableRow;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.CheckBoxTableCell;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    public class TableWithThumbnail extends Application {
      @Override
      public void start(Stage primaryStage) {
        final BorderPane root = new BorderPane();
        final TableView<Player> table = new TableView<Player>();
        table.setItems(createData());
        final TableColumn<Player, String> firstNameColumn = new TableColumn<>("First Name");
        final TableColumn<Player, String> lastNameColumn = new TableColumn<>("Last Name");
        final TableColumn<Player, Boolean> injuredColumn = new TableColumn<>("Injured");
        firstNameColumn.setCellValueFactory(new PropertyValueFactory<Player, String>("firstName"));
        lastNameColumn.setCellValueFactory(new PropertyValueFactory<Player, String>("lastName"));
        injuredColumn.setCellValueFactory(new PropertyValueFactory<Player, Boolean>("injured"));
        injuredColumn.setCellFactory(CheckBoxTableCell.forTableColumn(injuredColumn));
        injuredColumn.setEditable(true);
        table.setEditable(true);
        table.getColumns().addAll(Arrays.asList(firstNameColumn, lastNameColumn, injuredColumn));
        table.setRowFactory(new Callback<TableView<Player>, TableRow<Player>>() {
          @Override
          public TableRow<Player> call(TableView<Player> table) {
            return new PlayerTableRow();
        // Create a filtered list: only the injured players appear:
        final ObservableList<Player> injuredList = FXCollections.observableArrayList();
        buildInjuredList(table.getItems(), injuredList);
        table.getItems().addListener(new ListChangeListener<Player>() {
          @Override
          public void onChanged(ListChangeListener.Change<? extends Player> cahnge) {
            // Just rebuild injured list from scratch.
            // Might need to be more efficient: e.g. examine change(s) and update injuredList accordingly
            injuredList.clear();
            buildInjuredList(table.getItems(), injuredList);
        ListView<Player> injuredListView = new ListView<>(injuredList);
        // select and scroll in the table when selection changes in the list view:
        injuredListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Player>() {
          @Override
          public void changed(ObservableValue<? extends Player> observable, Player oldSelection,
              Player newSelection) {
            if (newSelection != null) {
              final int index = table.getItems().indexOf(newSelection);
              table.scrollTo(index);
              table.getSelectionModel().select(index);
        root.setCenter(table);
        root.setRight(injuredListView);
        final Scene scene = new Scene(root, 800, 250);
        scene.getStylesheets().add(getClass().getResource("tableWithThumbnail.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();  
      private void buildInjuredList(final ObservableList<Player> fullList, ObservableList<Player> injuredList) {
        for (Player player : fullList) {
          if (player.isInjured()) {
            injuredList.add(player);
      public static void main(String[] args) {
        launch(args);
      private ObservableList<Player> createData() {
        List<Player> players = Arrays.asList(
            new Player("Hugo" ,"Lloris", false),
            new Player("Brad", "Friedel", false),
            new Player("Kyle", "Naughton", false),
            new Player("Younes", "Kaboul", true),
            new Player("Benoit", "Assou-Ekotto", false),
            new Player("Jan", "Vertonghen", false),
            new Player("Michael", "Dawson", false),
            new Player("William", "Gallas", true),
            new Player("Kyle", "Walker", false),
            new Player("Scott", "Parker", false),
            new Player("Mousa", "Dembele", false),
            new Player("Sandro", "Cordeiro", true),
            new Player("Tom", "Huddlestone", false),
            new Player("Gylfi","Sigurdsson", false),
            new Player("Gareth", "Bale", false),
            new Player("Aaron", "Lennon", false),
            new Player("Paulinho", "Maciel", false),
            new Player("Jermane", "Defoe", false),
            new Player("Emmanuel", "Adebayor", true)
        // Note use of "extractor": this list will notify ListChangeListeners when the list changes, or when the
        // injuredProperty of any elements change
        ObservableList<Player> data =  FXCollections.<Player>observableArrayList(new Callback<Player, Observable[]>() {
          @Override
          public Observable[] call(Player player) {
            return new Observable[] {player.injuredProperty()};
        data.addAll(players);
        return data ;
      private static class PlayerTableRow extends TableRow<Player> {
        final String INJURED_STYLE_CLASS = "injured";
        final ChangeListener<Boolean> injuryListener = new ChangeListener<Boolean>() {
          @Override
          public void changed(ObservableValue<? extends Boolean> observable,
              Boolean oldValue, Boolean newValue) {
            if (newValue && !getStyleClass().contains(INJURED_STYLE_CLASS)) {
              getStyleClass().add(INJURED_STYLE_CLASS);
            } else {
              getStyleClass().remove(INJURED_STYLE_CLASS);
        @Override
        protected void updateItem(Player player, boolean empty) {
          if (getItem() != null) {
            getItem().injuredProperty().removeListener(injuryListener);
          super.updateItem(player, empty);
          if (player != null) {
            player.injuredProperty().addListener(injuryListener);
            if (player.isInjured()) {
              if (! getStyleClass().contains(INJURED_STYLE_CLASS)) {
                getStyleClass().add(INJURED_STYLE_CLASS);
            } else {
              getStyleClass().remove(INJURED_STYLE_CLASS);
          } else {
            getStyleClass().remove(INJURED_STYLE_CLASS);
      public static class Player {
        private final StringProperty firstName ;
        private final StringProperty lastName ;
        private final BooleanProperty injured ;
        Player(String firstName, String lastName, boolean international) {
          this.firstName = new SimpleStringProperty(this, "firstName", firstName);
          this.lastName = new SimpleStringProperty(this, "lastName", lastName);
          this.injured = new SimpleBooleanProperty(this, "injured", international);
        public String getFirstName() { return firstName.get(); }
        public void setFirstName(String firstName) { this.firstName.set(firstName);}
        public StringProperty firstNameProperty() { return firstName ; }
        public String getLastName() { return lastName.get(); }
        public void setLastName(String lastName) { this.lastName.set(lastName); }
        public StringProperty lastNameProperty() { return lastName ; }  
        public boolean isInjured() { return injured.get(); }
        public void setInjured(boolean international) { this.injured.set(international); }
        public BooleanProperty injuredProperty() { return injured ; }
        @Override
        public String toString() {
          return firstName.get() + " " + lastName.get();
    Here's the (very minimal) css file:
    @CHARSET "US-ASCII";
    .injured .table-cell {
    -fx-background-color: red;

  • Problem with objective-c troubleShooting

    Hi there,
    i'm all new to mac & iOS developement and am getting startet by working throught what appeared to be a great book "Einstieg in Objective-C 2.0 and Cocoa inkl iPhone programming".
    what im doing right now is creating an Weblog App for the iPhone by following stepBy step coding and interface instructions by this book.
    problem: everything seems to work just fine, i can compile and everything. but one funktion does not work which is creating a new article.
    the errorcode looks like that:
    +2011-01-25 14:59:28.775 WeblogClientTouch[12682:207] Fehler beim Anlegen eines neuen Artikels+
    and is produced by an NSLog:
    if (![managedObjectContext save:&error]) {
    NSLog(@"Fehler beim Anlegen eines neuen Artikels");
    so apparently the saving of a new entity 'article' does not work. here some code snippets that might help, first the function that creates a new article in which the error occurs:
    - (IBAction)neuerArtikel
    //erzeuge artikel
    NSEntityDescription *artikelDescription = [[fetchedResultsController fetchRequest]entity];
    NSManagedObject *newArtikel = [NSEntityDescription insertNewObjectForEntityForName:[artikelDescription name]
    inManagedObjectContext:managedObjectContext];
    //befülle artikel mit standardwerten
    [newArtikel setValue:NSLocalizedString(@"Neuer Artikel", nil)
    forKey:@"titel"];
    [newArtikel setValue:[NSDate date] forKey:@"datum"];
    [newArtikel setValue:@"Markus" forKey:@"autor"];
    //speichere artikel
    NSError *error;
    if (![managedObjectContext save:&error]) {
    NSLog(@"Fehler beim Anlegen eines neuen Artikels");
    //Tableview aktualisieren
    [self.tableView reloadData];
    in my datamodel i have only one entity named "Artikel" with the attributes: autor, titel, datum, inhalt.
    i would be very glad about some tips, because i've been trying to solve the problem for nearly 3 hours now and i dont think it can be that tricky..
    Message was edited by: sfluecki
    Message was edited by: sfluecki

    allRight.
    i got it working so far that there's no more errors.
    --> i can now klick on 'new article' without any errors, but my tableView does not show the new allocated articles
    --> after i restart the app (rebuild, reRun in simulator) the previously added articles are showing in the tableView.
    --> somehow my tableView does just update itself whilst starting the app.
    in the end of the 'addNewArticle' function i have the following:
    [self.tableView reloadData];
    the tableView itself is defined by the following:
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    NSArray *sections = [fetchedResultsController sections];
    NSUInteger count = 0;
    if ([sections count]) {
    id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:section];
    count = [sectionInfo numberOfObjects];
    return count;
    and
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    static NSString *CellIdentifier = @"Cell";
    //Zelle aus dem Cache holen oder erzeugen wenn nicht orhanden
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
    cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle
    reuseIdentifier:CellIdentifier] autorelease];
    NSManagedObject *artikel = [fetchedResultsController objectAtIndexPath:indexPath];
    //Titel als haupttext der zelle
    cell.textLabel.text= [artikel valueForKey:@"titel"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //Autor und Name als Detailtext der Zelle
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    NSString *dateString = [dateFormatter stringFromDate:[artikel valueForKey:@"datum"]];
    cell.detailTextLabel.text = [NSString stringWithFormat:NSLocalizedString(@"%@ am %@",nil), [artikel valueForKey:@"autor"], dateString];
    [dateFormatter release];
    return cell;
    whilst the function fetchedResultsController looks like this.
    - (NSFetchedResultsController *)fetchedResultsController
    if (fetchedResultsController != nil)
    return fetchedResultsController;
    //FetchRequest initialisieren
    NSFetchRequest *fetchedRequest = [NSFetchRequest new];
    NSEntityDescription *artikelDescription = [NSEntityDescription entityForName:@"Artikel"
    inManagedObjectContext:managedObjectContext];
    [fetchedRequest setEntity:artikelDescription];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"datum" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
    [fetchedRequest setSortDescriptors:sortDescriptors];
    //FetchedResultsController initialisieren
    fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchedRequest
    managedObjectContext:managedObjectContext
    sectionNameKeyPath:nil
    cacheName:@"Overview" ];
    fetchedResultsController.delegate = self;
    //aufräumen
    [fetchedRequest release];
    [sortDescriptor release];
    [sortDescriptors release];
    return fetchedResultsController;
    i'm sorry to bother you with that lot of code.. but i'm stuck here since now 8h,
    and wouldnt probably be any step further without your help in the first place,
    so thanks a lot for the first inputs =)

  • UITableView Search Controller & Heading Titles (iPhone OS 3.1)

    +More of a continuation from a previous thread to discuss a more specific issue+
    → Ray,
    I could never get the Sections project to work. I had checked the code, but it still didn't load.
    I had tried taking some code out of the book. The initial problems came in the fact that the book used an NSDictionary, and some dictionary specific code, whereas I'm using an array.
    In addition, I had taken some code out of Apple's TableSearch sample project, which, among other things, uses a UISearchDisplayController, which is different from the Sections project.
    Basically, for the section headings I'm just interested in grabbing the first character in the person object's name, matching it against existing NSStrings in an array, and if it's a different letter, then adding it to the array. The end result should be similar to the built-in Contacts application, assuming that you don't have a contact for every single letter of the alphabet.
    I don't want an index, as that would interfere with the detail disclosure buttons (as per the HIG).
    Finally, the table is implemented so that it loads a second view based on an objectAtIndex of indexPath.row. The only issue is that when searching it still references the initial array, and so it displays the wrong second level control. I was thinking of implementing a flag which I could check in tableView:didSelectRowAtIndexPath, but I don't know of any isSearching method or equivalent. As before, I'm using a Search Display Controller instead of merely a search bar, which is what the Sections project uses.
    Message was edited by: musicwind95

    Ok, here's an edit of your EmployeeViewController class that shows how to implement section headers (Person.m is also included to correct a couple minor memory management problems I noticed, but those have nothing to do with our main topic):
    // EmployeesViewController.h
    #import <UIKit/UIKit.h>
    @interface EmployeesViewController : UITableViewController <UISearchDisplayDelegate, UISearchBarDelegate> {
    NSArray *initArray; // <-- added master data array
    NSDictionary *listContent; // Master data content <-- changed to dictionary
    NSDictionary *filteredListContent; // Filtered content as a result of a search <-- changed to dictionary
    // The saved state of the search in case of a memory warning
    NSString *savedSearchTerm;
    BOOL searchWasActive;
    BOOL searchIsActive;
    // NSString *employeeName;
    @property (nonatomic, retain) NSArray *initArray; // <-- added master data array
    @property (nonatomic, retain) NSDictionary *listContent; // <-- changed to dictionary
    @property (nonatomic, retain) NSDictionary *filteredListContent; // <-- changed to dictionary
    @property (nonatomic, copy) NSString *savedSearchTerm;
    @property (nonatomic) BOOL searchWasActive;
    @property (nonatomic) BOOL searchIsActive;
    @end
    // EmployeesViewController.m
    #import "EmployeesViewController.h"
    // #import "NSDictionary-MutableDeepCopy.h" <-- not needed
    #import "Person.h"
    // #import "Constants.h" <-- not needed
    #import "EmployeesDetailController.h"
    // #import "EmployeeJobsController.h" <-- not needed
    @implementation EmployeesViewController
    @synthesize initArray; // <-- added master data array
    @synthesize listContent;
    @synthesize filteredListContent;
    @synthesize savedSearchTerm;
    @synthesize searchWasActive;
    @synthesize searchIsActive;
    #pragma mark -
    #pragma mark Custom Methods
    // --> added helper method to handle openURL:tel: failure
    - (void)openTelURLFailed:(Person*)person {
    NSString *device = [UIDevice currentDevice].model;
    NSLog(@"Call could not be successfully opened. This device is an %@", device);
    // TODO: Does this message comply with HIG? If user can't do anything, why display the alert?
    // --> It's correct to let the user know why the call failed and ask the user to acknowledge this
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Could not open Phone application"
    message:[NSString stringWithFormat:
    @"The phone call to %@
    could not be placed because your %@ does not have a Phone application.",
    [person employeeName], [person telephoneNumber], device]
    delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
    // --> added helper method to make alphabetic dictionary from sorted array of Person objects
    - (NSDictionary)getDictionaryFromArray:(NSArray)personArray {
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:26];
    for (Person *p in personArray) {
    // get the first initial of employeeName as an uppercase string
    NSString *name = [p.employeeName capitalizedString];
    if (![name length]) continue;
    NSString *initial = [name substringToIndex:1];
    NSMutableArray *array = [dict objectForKey:initial];
    if (array == nil) {
    // add new key-array pair to the dictionary
    array = [NSMutableArray arrayWithCapacity:[personArray count]];
    [dict setObject:array forKey:initial];
    // add current Person object to the array for first initial of name
    [array addObject:p];
    return [NSDictionary dictionaryWithDictionary:dict];
    // --> added helper method to get the array of Person objects for a given table and section no.
    - (NSArray)getListForTableView:(UITableView)tableView section:(NSUInteger)section {
    NSDictionary *dict = tableView == self.searchDisplayController.searchResultsTableView ? filteredListContent : listContent;
    NSString *key = [[[dict allKeys] sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:section];
    return [dict objectForKey:key];
    #pragma mark -
    #pragma mark Lifecycle Methods
    - (void)viewDidLoad {
    // Create dummy data set --> start abbreviated code block
    NSArray *jobs = [[NSArray alloc] initWithObjects: // ...
    NSArray *alex = [[NSArray alloc] initWithObjects: // ...
    NSArray *turner = [[NSArray alloc] initWithObjects: // ...
    NSArray *initContents = [[NSArray alloc] initWithObjects:
    [Person personWithContentsOfArray:alex],
    [Person personWithContentsOfArray:turner],
    nil];
    self.initArray = initContents; // <-- save master data array
    self.listContent = [self getDictionaryFromArray:initArray]; // <-- dictionary
    [alex release];
    [turner release];
    // --> end abbreviated code block - all other code in this file may be copied verbatim
    [jobs release];
    [initContents release];
    // Create a filtered list that will contain products for the search results table <-- not needed here
    // Restore search settings if previously saved
    if (self.savedSearchTerm){
    [self.searchDisplayController setActive:self.searchWasActive];
    [self.searchDisplayController.searchBar setText:savedSearchTerm];
    self.savedSearchTerm = nil;
    [self.tableView reloadData];
    self.tableView.scrollEnabled = YES;
    self.searchIsActive = NO;
    - (void)viewDidUnload {
    self.filteredListContent = nil;
    self.searchIsActive = NO;
    - (void)viewDidDisappear:(BOOL)animated {
    // Save the state of the search
    self.searchWasActive = [self.searchDisplayController isActive];
    self.savedSearchTerm = [self.searchDisplayController.searchBar text];
    self.searchIsActive = NO;
    - (void)dealloc {
    [savedSearchTerm release]; // <-- release retained string
    [listContent release];
    [filteredListContent release];
    [initArray release]; // <-- release master data array
    [super dealloc];
    #pragma mark -
    #pragma mark UITableView data source and delegate methods
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSDictionary *dict = tableView == self.searchDisplayController.searchResultsTableView ? filteredListContent : listContent; // <-- get dictionary
    return [[dict allKeys] count]; // <-- return number of keys in dictionary
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // If the requested table view is the search controller's view, return the count of the filtered list; otherwise, return the count of the main list
    NSArray *list = [self getListForTableView:tableView section:section]; // <-- get array for section
    return [list count]; // <-- return row count for section
    // --> added to implement section headers
    - (NSString)tableView:(UITableView)tableView titleForHeaderInSection:(NSInteger)section {
    NSDictionary *dict = tableView == self.searchDisplayController.searchResultsTableView ? filteredListContent : listContent;
    NSArray *allKeys = [dict allKeys];
    if ([allKeys count] == 0)
    return @"";
    return [[allKeys sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:section];
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
    if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellID] autorelease];
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    // If the requesting table view is the search controller's table, configure the cell using the filtered content; otherwise, use the main list
    NSArray *list = [self getListForTableView:tableView section:indexPath.section]; // <-- get array for section
    Person *person = [list objectAtIndex:indexPath.row]; // <-- get person for row
    cell.textLabel.text = person.employeeName;
    cell.detailTextLabel.text = person.telephoneNumber;
    return cell;
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog (@"searchIsActive: %d", self.searchIsActive); // <-- %d
    // if (self.searchIsActive == NO) { // <-- = > -- }
    // rewrite to consolidate code:
    NSArray *list = [self getListForTableView:tableView section:indexPath.section]; // <-- get array for section
    Person *person = [list objectAtIndex:indexPath.row];
    NSString *phoneNumberToDial = [NSString stringWithFormat:@"tel:%@", [person telephoneNumber]];
    NSURL *callURL = [[NSURL alloc] initWithString:phoneNumberToDial];
    if ([[UIApplication sharedApplication] openURL:callURL])
    NSLog(@"Call initialized properly.");
    else
    [self openTelURLFailed:person];
    [callURL release];
    - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    NSArray *list = [self getListForTableView:tableView section:indexPath.section]; // <-- get array for section
    EmployeesDetailController *detailView = [[EmployeesDetailController alloc] dataFromPerson:[list objectAtIndex:indexPath.row]]; // <--
    [self.navigationController pushViewController:detailView animated:YES];
    [detailView release]; // <-- uncomment
    #pragma mark -
    #pragma mark Content Filtering
    - (void)filterContentForSearchText:(NSString *)searchText {
    // Update the filtered array based on the search text and scope
    // Clear the filtered array <-- the filtered array is now local
    NSMutableArray *filteredArray = [NSMutableArray arrayWithCapacity:[self.initArray count]];
    // Search the main list for products whose name matches searchText, and add matching items to the filtered array
    for (Person *person in initArray) { // <-- traverse the master data array
    NSComparisonResult resultName = [person.employeeName compare:searchText options:(NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
    NSComparisonResult resultPhone = [person.telephoneNumber compare:searchText options:(NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
    if (resultName == NSOrderedSame || resultPhone == NSOrderedSame) {
    [filteredArray addObject:person];
    self.filteredListContent = [self getDictionaryFromArray:filteredArray]; // <-- get filtered dictionary from filtered array
    self.searchIsActive = YES;
    #pragma mark -
    #pragma mark UISearchDisplayController Delegate Methods
    - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    [self filterContentForSearchText:searchString];
    self.searchIsActive = YES;
    // Return YES to force the table view to be reloaded
    return YES;
    - (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {
    self.searchIsActive = YES;
    @end
    // Person.m
    #import "Person.h"
    @implementation Person
    +(id)personWithContentsOfArray:(NSArray *)initArray {
    Person *myPerson = [[[Person alloc] init] autorelease]; // <-- convenience method should autorelease
    return myPerson;
    - (void)dealloc { // <-- release all retained ivars
    [employeeName release];
    [telephoneNumber release];
    [employeeEmail release];
    [employeeJobs release];
    [super dealloc];
    @end
    The above doesn't do anything about saving or retrieving persistent data. Instead of using the plist structure described previously, the example just converts your dummy array to a dictionary. I decided not to replace the dummy array with a more natural structure after giving some thought to where the overall app might be headed. Considering the Employee section in isolation, the plist is a natural fit. But the finance tab tells us you're probably going to need a database. If that's the case the dummy array might as well stay in place until we know more about the overall data requirements (I can only hope you haven't promised anyone a one-off iPhone port of QuickBooks for Father's Day).
    - Ray

  • Back button not removing from the stack?

    Hi,
    I have the following code:
    [[self navigationController]pushViewController:_newsDetailController animated:YES];
    However, It doesn't seem to be removing from the stack when the user hits the back button on the UINavigationBar.
    The reason I believe this, is because when you then select another item in my UITableView, it loads exactly the same details as the first time.
    I have tried [_newsDetailController release]; but it still doesn't make any difference. It just crashes after the third selection.
    This is what I'm doing in my didSelectRowAtIndexPath:
    - (void)tableViewUITableView *)tableView didSelectRowAtIndexPathNSIndexPath *)indexPath {
    [[self appDelegate] setCurrentlySelectedBlogItem:[[[self rssParser]rssItems]objectAtIndex:indexPath.row]];
    [self.appDelegate loadNewsDetails];
    Any help would be greatly appreciated. I've spent ages on this!
    It worked fine until I added a UINavigationController.
    Thanks,
    Nick

    Hi Nick, and welcome to the Dev Forum,
    nrawlins wrote:
    ... It doesn't seem to be removing from the stack when the user hits the back button on the UINavigationBar.
    I understand how your observations could make it seem like your _newsDetailController is somehow staying on the stack, but that's not what's going on here. If you want to see the stack, just add some logging before and after pushing or popping:
    NSLog(@"stack: %@", self.navigationController.viewControllers);
    I think we'll need to see more of your code to isolate the problem, but what we're looking for is a logic mistake which causes the detail controller to always display the info for the same item, regardless of which item is selected next. Here's a list of questions to guide your search, and/or show you which code we need to look at:
    1) What's in the array returned by [[self rssParser]rssItems] ? It might help to add some logging in tableView:didSelectRowAtIndexPath like this:
    - (void)tableView(UITableView *)tableView didSelectRowAtIndexPath(NSIndexPath *)indexPath {
    NSArray *item = [[[self rssParser]rssItems]objectAtIndex:indexPath.row]];
    NSLog(@"%s: item=%@", _func_, item);
    [[self appDelegate] setCurrentlySelectedBlogItem:item];
    [[self appDelegate] loadNewsDetails];
    2) What does loadNewsDetails do? It looks like it finds the details for the item stored in currentlySelectedBlogItem. Is that right? Some logging in loadNewsDetails might help to make sure the correct details are loaded there. From your description it sounds like you already had this part of the code working right, but it wouldn't hurt to be sure it's still doing what you expect;
    3) How does the data obtained in loadNewsDetails find its way to the details controller? This is the missing link not shown in the code you've posted so far. I think we need to look at:
    3.1) Where and when the details controller is created;
    3.2) Whether the same controller object is intended to persist from item to item, or whether a new instance of the controller is created each time an item is selected. The latter scheme is usually preferred for best memory management;
    3.3) Is the current item and detail data stored in the detailsController or the app delegate? When is it stored, and when is it used?
    For example, suppose the details controller is only created once and persists for the life of the table view. Then suppose loadNewDetails saves the new details in an ivar of the app delegate, and the code to fetch the new details is in viewDidLoad of the controller.
    In the above scenario, viewDidLoad would run after the details controller was created, and if the details of the first selection were loaded by then, the details for the currently selected item would
    be presented as expected. But viewDidLoad will normally only run once, so when the selection was changed, the new details would never be fetched, and the previous details will be displayed again.
    The best way to avoid this and other related scenarios, is to create a new details controller each time a new selection is made from the table view:
    // MyTableViewController.m
    #import "myAppDelegate.h"
    #import "NewsDetailController.h"
    // called by loadNewsDetails as soon as details have been loaded
    - (void)presentDetailController {
    NewsDetailController *viewController = [[NewsDetailController alloc] // vc retainCount is 1
    initWithNibName:@"NewsDetailController" bundle:nil];
    // store new details in the detail controller; e.g.:
    viewController.navigationItem.title = [self appDelegate].currentlySelectedBlogItem;
    viewController.textView = [self appDelegate].currentDetails;
    [self.navigationController pushViewController:viewController // vc retainCount is 2
    animated:YES];
    [release viewController]; // vc retainCount is 1
    By releasing the new controller in the last line, we reduce its retain count to 1. Now the new controller is only retained by the stack, so when the stack is popped, the new controller will be dealloced.
    If none of the above is helpful, please answer all the questions as best you can and post the indicated code, ok?
    - Ray

  • NSInvalidArgumentException when using NSDictionary

    Hello all,
    I am getting "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFType objectForKey:]: unrecognized selector sent to instance 0x451920'" When trying to execute the following code (where letter returns an NSString):
    called within a function to get a score for a letter:
    NSString *letter = [[gamePieces objectAtIndex:i] letter];
    NSString *letterValue = [self getScoreForLetter:letter];
    -(NSObject)getScoreForLetter:(NSObject)key
    NSLog(@"got here with key: %@", key);
    NSString *value = [dictionary objectForKey:key];
    return value;
    How the dictionary object is populated:
    -(void)initLetterScores
    NSArray *keys = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", nil];
    NSArray *objects = [NSArray arrayWithObjects:@"100", @"300", @"300", @"200", @"100", @"400", @"200", @"400", @"100", @"800", @"500", @"100", @"300", @"100", @"100", @"300", @"1000", @"100", @"100", @"100", @"100", @"400", @"100", @"800", @"400", @"1000", nil];
    dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    }

    Hi, in the last line of code
    dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    the created dictionary is an autoreleased object.
    You should use
    dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
    I suggest reading the Memory Management Programming Guide for Cocoa if this is new to you: https://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/Memory Mgmt/MemoryMgmt.html

  • Populated TableView in a BorderPane

    Hi everyone,
    I have a populated TableView object which I have added to my BorderPane layout. More specifically, this table is added to the center pane of the BorderPane object.
    As-is, this table only occupies 300px * 300px of this center pane. Is there a behavior enabling the table to use up all the space in the center pane?
    Code segment:
    @Override
         public void start(Stage stage) throws Exception {
              // instantiate group and add widget as root node
              Group rootNode = new Group();
                    BorderPane layout_main = new BorderPane(); // base layout for application           
                    TableView<Person>table = new TableView<Person>(); // instantiate a table of 'Person' objects
                    TableColumn<Person>column_name = new TableColumn<Person>("Name"); // only 1 column...'name'
                    column_name.setProperty("name");
                    // instantiate list to store 'person' objects
                    ObservableList<Person>list = FXCollections.observableArrayList();
              // code for populating list...
                    // add list to table as well as column
                    table.setItems(list);
              table.getColumns().addAll(column_name);
                    // set the populated table to the center pane
                    // CONCERN:
                    // ... can this table span the entire center of the layout?
                    // why is it only taking up a small region of the center pane?
              layout_main.setCenter(table);
                    rootNode.getChildren().add(layout_main);
              // declare behaviors of the scene, and make visible
              Scene scene = new Scene(rootNode);
              stage.setScene(scene);
              stage.setWidth(600);
              stage.setHeight(600);
              stage.setTitle("Example Application");
              stage.setVisible(true);
         }I'd be very appreciative for any leads.
    Thank you,
    p.

    Try to use your BorderPane directly as a scene root, eliminating Group at all.
    I mean instead of:
    rootNode.getChildren().add(layout_main);
    Scene scene = new Scene(rootNode);Just use:
    Scene scene = new Scene(layout_main);

  • Problem while populating RFC table into HTMLB tableView control

    Hi, We are trying to populate some data from R/3 into the front end. For this we are using tableView control in HTMLB. But the problem is, one particular field is behaving strangely where as all other fields are displayed correctly. This value is sometimes displayed correctly and sometimes not. The FM if executed at the back end is giving correct result always. In Java there is a single line code i.e. table.getString("FIELD_NAME_IN_RFC");. Please guide us to find out the problem if somebody has already faced this before.

    Hi, We are trying to populate some data from R/3 into the front end. For this we are using tableView control in HTMLB. But the problem is, one particular field is behaving strangely where as all other fields are displayed correctly. This value is sometimes displayed correctly and sometimes not. The FM if executed at the back end is giving correct result always. In Java there is a single line code i.e. table.getString("FIELD_NAME_IN_RFC");. Please guide us to find out the problem if somebody has already faced this before.

  • SIGABRT error when choosing a row of a tableview

    Hello, I am creating an iPhone app and I keep getting a "SIGABRT" error. I have a tableview where I want a separate webpage pushed for each rows.
    Currently, what happens is that the table displays; however, when I pick a row it gives me a SIGABRT error. Please help.
    Here is my first view (table view) .h file:
    #import <UIKit/UIKit.h>
    @interface videoTableViewController : UITableViewController
        NSArray *videos;
    @property (strong, nonatomic) NSArray *videos;
    @end
    Here is my first view (table view) .m file:
    #import "videoTableViewController.h"
    #import "videoURLController.h"
    @interface videoTableViewController ()
    @end
    @implementation videoTableViewController
    @synthesize videos;
    - (id)initWithStyle:(UITableViewStyle)style
        self = [super initWithStyle:style];
        if (self) {
            // Custom initialization
        return self;
    - (void)viewDidLoad
        [super viewDidLoad];
        videos = [NSArray arrayWithObjects:@"Welcome", @"Hello", @"Goodbye", nil];
        // Uncomment the following line to preserve selection between presentations.
        // self.clearsSelectionOnViewWillAppear = NO;
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    - (void)viewDidUnload
        [super viewDidUnload];
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    #pragma mark - Table view data source
    - (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.
        return [self.videos count];
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        static NSString *CellIdentifier = @"videoCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        // Configure the cell...
        NSUInteger row = [indexPath row];
        cell.textLabel.text = [videos objectAtIndex:row];
        if (row == 0)
            cell.detailTextLabel.text = @"Welcome";
        if (row == 1)
            cell.detailTextLabel.text = @"What we value";
        if (row == 2)
            cell.detailTextLabel.text = @"What does Honor mean?";
        return cell;
    // 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;
    #pragma mark - Table view delegate
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
         videoURLController *detailViewController = [[videoURLController alloc] initWithNibName:@"videoTableViewController" bundle:nil];
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
        if (indexPath.row == 0){
            [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]];
         // Pass the selected object to the new view controller.
         [self.navigationController pushViewController:detailViewController animated:YES];
    @end
    Here is my videoURLController (second view/web view) .h file?
    #import <UIKit/UIKit.h>
    @interface videoURLController : UIViewController
    @property (strong, nonatomic) IBOutlet UIWebView *webView;
    @end
    Here is my videoURLController (second view/web view) .m file?
    #import "videoURLController.h"
    @interface videoURLController ()
    @end
    @implementation videoURLController
    @synthesize webView;
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
        return self;
    - (void)viewDidLoad
        [super viewDidLoad];
      // Do any additional setup after loading the view.
    - (void)viewDidUnload
        [super viewDidUnload];
        // Release any retained subviews of the main view.
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    @end

    Hello, I am creating an iPhone app and I keep getting a "SIGABRT" error. I have a tableview where I want a separate webpage pushed for each rows.
    Currently, what happens is that the table displays; however, when I pick a row it gives me a SIGABRT error. Please help.
    Here is my first view (table view) .h file:
    #import <UIKit/UIKit.h>
    @interface videoTableViewController : UITableViewController
        NSArray *videos;
    @property (strong, nonatomic) NSArray *videos;
    @end
    Here is my first view (table view) .m file:
    #import "videoTableViewController.h"
    #import "videoURLController.h"
    @interface videoTableViewController ()
    @end
    @implementation videoTableViewController
    @synthesize videos;
    - (id)initWithStyle:(UITableViewStyle)style
        self = [super initWithStyle:style];
        if (self) {
            // Custom initialization
        return self;
    - (void)viewDidLoad
        [super viewDidLoad];
        videos = [NSArray arrayWithObjects:@"Welcome", @"Hello", @"Goodbye", nil];
        // Uncomment the following line to preserve selection between presentations.
        // self.clearsSelectionOnViewWillAppear = NO;
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    - (void)viewDidUnload
        [super viewDidUnload];
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    #pragma mark - Table view data source
    - (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.
        return [self.videos count];
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        static NSString *CellIdentifier = @"videoCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        // Configure the cell...
        NSUInteger row = [indexPath row];
        cell.textLabel.text = [videos objectAtIndex:row];
        if (row == 0)
            cell.detailTextLabel.text = @"Welcome";
        if (row == 1)
            cell.detailTextLabel.text = @"What we value";
        if (row == 2)
            cell.detailTextLabel.text = @"What does Honor mean?";
        return cell;
    // 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;
    #pragma mark - Table view delegate
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
         videoURLController *detailViewController = [[videoURLController alloc] initWithNibName:@"videoTableViewController" bundle:nil];
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
        if (indexPath.row == 0){
            [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]];
         // Pass the selected object to the new view controller.
         [self.navigationController pushViewController:detailViewController animated:YES];
    @end
    Here is my videoURLController (second view/web view) .h file?
    #import <UIKit/UIKit.h>
    @interface videoURLController : UIViewController
    @property (strong, nonatomic) IBOutlet UIWebView *webView;
    @end
    Here is my videoURLController (second view/web view) .m file?
    #import "videoURLController.h"
    @interface videoURLController ()
    @end
    @implementation videoURLController
    @synthesize webView;
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
        return self;
    - (void)viewDidLoad
        [super viewDidLoad];
      // Do any additional setup after loading the view.
    - (void)viewDidUnload
        [super viewDidUnload];
        // Release any retained subviews of the main view.
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    @end

  • Problems loading text to xib using plist in tableview's selected cell

    I am developing an app that starts with a grouped tableview cell.  Each cell has an image, text, and description from a plist.  When a cell is chosen a xib is loaded by a view controller in the plist.  I want to load into the xib some text, an image, and a sound file that is in the plist (dict for that cell).  This way I don't have to have lots of view controllers and xibs.  I have been able to load the xib using this method but I can't get the images and text to load.  I have been able to do it when I don't have a grouped table view but when I add the grouping in the plist the connection is lost.  below is my code.  Could someone look at it and tell me where I've gone wrong, how to correct it, or another way to do what I want to do?
    I know I am not calling the right array and then dictionary but I don't know how to correct this.  Help please.
    //  RootViewController.h
    //  TableViewPush
    #import <UIKit/UIKit.h>
    @interface RootViewController :  UITableViewController <UITableViewDelegate, UITableViewDataSource>  {
    NSArray *tableDataSm;
    @property (nonatomic, retain) NSArray *tableDataSm;
    @end
    //  RootViewController.m
    //  TableViewPush
    #import "RootViewController.h"
    #import "Location One.h"
    #import "HowToUseViewController.h"
    #import "TableViewPushAppDelegate.h"
    @implementation RootViewController
    @synthesize tableDataSm;
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        const NSDictionary *const row = [self rowForIndexPath:indexPath];
        NSString *wantedClassName = [row objectForKey:@"controller"];
        UIViewController *const vc = [[NSClassFromString (wantedClassName) alloc] init];
        NSLog(@"controller is -%@-", wantedClassName);
        [self.navigationController pushViewController:vc animated:YES];
        TableViewPushAppDelegate *appDelegate = ( TableViewPushAppDelegate *)[[UIApplication sharedApplication]delegate];
        appDelegate.myImage = [[NSString alloc]initWithFormat:@"%@",[[tableDataSm objectAtIndex:indexPath.row]objectForKey:@"picture"]];
    NSLog(@"%@", appDelegate.myImage);
    appDelegate.textView = [[NSString alloc]initWithFormat:@"%@",[[tableDataSm objectAtIndex:indexPath.row]objectForKey:@"description"]];
        [vc release];
    //  TableViewPushAppDelegate.h
    //  TableViewPush
    #import <UIKit/UIKit.h>
    @class RootViewController, HowToUseViewController;
    @interface TableViewPushAppDelegate : UIViewController <UIApplicationDelegate>  {
        NSString *myImage;
        NSString *textView;
        UIWindow *window;
        UINavigationController *navigationController;
        HowToUseViewController *howToUseViewController;
    @property (nonatomic, retain) IBOutlet UIWindow *window;
    @property (nonatomic, retain) IBOutlet RootViewController *viewController;
    @property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
    @property(retain,nonatomic)NSString *myImage;
    @property(retain,nonatomic)NSString *textView;
    @end
    //  TableViewPushAppDelegate.m
    //  TableViewPush
    #import "TableViewPushAppDelegate.h"
    #import "RootViewController.h"
    @implementation TableViewPushAppDelegate
    @synthesize window;
    @synthesize navigationController;
    @synthesize viewController;
    @synthesize myImage;
    @synthesize textView;
    //  Location One.h
    //  TableViewPush
    #import <UIKit/UIKit.h>
    #import "RootViewController.h"
    @interface   Location_One: UIViewController  {
        IBOutlet UIImageView *imageOne;
    IBOutlet UITextView  *textViewTwo;
    @property (nonatomic, retain) UITextView *textViewTwo;
    @property (nonatomic, retain) UIImageView *imageOne;
    @end
    //  Location One.m
    //  TableViewPush
    #import "Location One.h"
    #import "TableViewPushAppDelegate.h"
    @implementation Location_One
    @synthesize textViewTwo;
    @synthesize imageOne;
    -(id) init{
        if((self = [super initWithNibName:@"Location One" bundle:nil])){
        return self;
    - (void)viewDidLoad {
           NSLog(@"InView did load");
    [super viewDidLoad];
        TableViewPushAppDelegate *appDelegate = (TableViewPushAppDelegate *)[[UIApplication sharedApplication]delegate];
    textViewTwo.text = [[NSString alloc] initWithFormat:@"%@", appDelegate.textView];
    NSString *path = [[NSString alloc]initWithFormat:@"%@",appDelegate.myImage];
    UIImage *img = [UIImage imageNamed:path];
        [imageOne setImage:img];
    plist 
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <array>
         <dict>
              <key>header</key>
              <string>85710</string>
              <key>rows</key>
              <array>
                   <dict>
                        <key>text</key>
                        <string>52 Glass Illusions Studio</string>
                        <key>detailText</key>
                        <string>150 S Camino Seco, #119</string>
                        <key>image</key>
                        <string>VisualFEight.png</string>
                        <key>controller</key>
                        <string>Location_One</string>
                        <key>picture</key>
                        <string>VisualOne.png</string>
                        <key>audio</key>
                        <string>AudioOne.mp3</string>
                        <key>description</key>
                        <string>TextOne</string>
                   </dict>

    I think you problem lies in this part.
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
        const NSDictionary *const row = [self rowForIndexPath:indexPath];
        NSString *wantedClassName = [row objectForKey:@"controller"];
        UIViewController *const vc = [[NSClassFromString (wantedClassName) alloc] init];
        NSLog(@"controller is -%@-", wantedClassName);
        [self.navigationController pushViewController:vc animated:YES];
        TableViewPushAppDelegate *appDelegate = ( TableViewPushAppDelegate *)[[UIApplication sharedApplication]delegate];
        appDelegate.myImage = [[NSString alloc]initWithFormat:@"%@",[[tableDataSmobjectAtIndex:indexPath.row]objectForKey:@"picture"]];
    NSLog(@"%@", appDelegate.myImage);
    appDelegate.textView = [[NSString alloc]initWithFormat:@"%@",[[tableDataSm objectAtIndex:indexPath.row]objectForKey:@"description"]];
        [vc release];
    specifically the underlined part.  does this need modifying or completely rewritten.

  • How can I select text in a thtmlb:tableview in a pop-up?

    Hi,
    We have a number of pop-up screens that contain thtmlb:tableview tags.  For some reason, it is not possible to select text (left-mouse click then drag cursor) in these pop-ups.  We are currently having to put any text that the user might want to select in disabled inputfields, but this looks rather ugly. 
    Does anyone have a solution to this problem?  The selection of text within tableviews works fine if the view isn't displayed in a pop-up.
    Many thanks,
    Andrew

    HI Andrew,
    I have a littel problem in understanding the business use case.
    Why should the user want to copy the text from the view.He will either select a row,by using the seletion tabs at the side of the view.
    But why woudl he actually copy the text by left clicking and dragging the mouse over the text.Doesn't look like a valid use case.
    What i have implemened once is where the table in the pop up contains multiple fields,and the user wants the description (ie one field) to be populated automatically into the field after selection of that row in the table view.Thsi can be eaqsily achived by making the table view select option as true and changing the html code also to fetch the selected index.
    After this, the selected entity can be obtained from the collection wrapper,since it becomes the current entity:
    me->typed_context->(context node name)->collection wrapper->get_current()
    Now the desired field from this entity can be copied into the field of your choice in the parent view.Also once the user clicks the selection tab to select the enitty,popup_close method shoudl be called and pop up shoudl be closed immediately.
    All this processing should happen in an even handler eh_onselect().

  • TableView - How to update a running balance column after any other column in the view is re-sorted

    To keep this simple and to illustrate a problem that I am trying to solve let's say we have
    a domain class that contains an income per day.
    This class has two persistent properties - populated from a database table - date and income.
    And there is one transient property - running balance - that shows the accumulated income
    starting from the first record. This property is not persisted and it is used only to show
    the running/accumulated income in a table view.
    This domain object is shown in a table view with three columns:
         - date
         - income
         - running balance
    The first two columns - date and income - are sortable. When the user clicks on the column
    heading these can will be sorted in ascending or descending order. The running balance
    column needs to reflect this change and be correctly updated.
    So the question is : how would you implement the running balance update after the data in
    the table has been updated by the user?
    Take 1)
    =============
    The obvious approach is to use "setOnSort" method to consume the SortEvent event and re-sort the
    data but the sort-event does not contain any useful information that would tell from which column
    the sort event originated.
    Take 2)
    =============
    Found a possible solution:
         - TableView.getSortOrder() returns a list that defines the order in which TableColumn instances are sorted after the user clicked one or more column headings.
         - TableColumn.getSortType() returns the sort type - ascending/descending.
         - This info can be used in the TableView.setOnSort() event handler to re-sort the data and update the balance at the same time.
    Take 3)
    =============
    When the TableView.setOnSort() event handler is called the data is already sorted therefore the only thing that needs to be done is to update the running balance.

    I  think I understand what you're trying to do. If I've missed it, apologies, but I think this will provide you with something you can work from anyway.
    I would listen to the data instead of watching specifically for sorting. This will be much more robust if you add new functionality later (such as adding and removing rows, editing the data that's there, etc).
    Specifically, for the runningBalance column, create a cellValueFactory that provides a DoubleBinding; this binding should listen for changes to the data and compute the value by running through the table's items up to the point of the item for which it's displaying the value. (Hope you can untangle that sentence.)
    Example. The important part is the cellValueFactory for the cumulativeAmountCol. I guess I should mention that you shouldn't try this exact approach with very large tables as the performance might be pretty bad (computations of the order of n x m on changing data, where n is the number of rows in the table and m is the number of visible rows in the table).
    import java.text.DateFormat;
    import java.text.NumberFormat;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Random;
    import javafx.application.Application;
    import javafx.beans.Observable;
    import javafx.beans.binding.DoubleBinding;
    import javafx.beans.property.DoubleProperty;
    import javafx.beans.property.ObjectProperty;
    import javafx.beans.property.SimpleDoubleProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.FXCollections;
    import javafx.scene.Scene;
    import javafx.scene.control.TableCell;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableColumn.CellDataFeatures;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    public class CumulativeTableColumnExample extends Application {
      private final static int NUM_ITEMS = 20 ;
    @Override
      public void start(Stage primaryStage) {
      final TableView<LineItem> table = new TableView<>();
      // using the extractor here makes sure the table item list fires a list changed event if any amounts change
      // this enables the cumulative amount column to keep up to date when the amount in a different row changes.
      table.setItems(FXCollections.observableList(createRandomData(), new Callback<LineItem, Observable[]>() {
          @Override
          public Observable[] call(LineItem item) {
            return new Observable[] {item.amountProperty()};
      final TableColumn<LineItem, Date> dateCol = new TableColumn<>("Date");
      final TableColumn<LineItem, Number> amountCol = new TableColumn<>("Amount");
      final TableColumn<LineItem, Number> cumulativeAmountCol = new TableColumn<>("Cumulative Amount");
      table.getColumns().addAll(Arrays.asList(dateCol, amountCol, cumulativeAmountCol));
      dateCol.setCellValueFactory(new PropertyValueFactory<LineItem, Date>("date"));
        amountCol.setCellValueFactory(new PropertyValueFactory<LineItem, Number>("amount"));
        cumulativeAmountCol.setCellValueFactory(new PropertyValueFactory<LineItem, Number>("amount"));
        cumulativeAmountCol.setSortable(false); // otherwise bad things might happen
      final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
      dateCol.setCellFactory(new Callback<TableColumn<LineItem, Date>, TableCell<LineItem, Date>>() {
          @Override
          public TableCell<LineItem, Date> call(TableColumn<LineItem, Date> col) {
            return new TableCell<LineItem, Date>() {
              @Override
              public void updateItem(Date date, boolean empty) {
                super.updateItem(date, empty);
                if (empty) {
                  setText(null);
                } else {
                  setText(dateFormat.format(date));
      cumulativeAmountCol.setCellValueFactory(new Callback<CellDataFeatures<LineItem, Number>, ObservableValue<Number>> () {
          @Override
          public ObservableValue<Number> call(CellDataFeatures<LineItem, Number> cellData) {
            final LineItem currentItem = cellData.getValue() ;
            DoubleBinding value = new DoubleBinding() {
                super.bind(table.getItems());
              @Override
              protected double computeValue() {
                double total = 0 ;
                LineItem item = null ;
                for (Iterator<LineItem> iterator = table.getItems().iterator(); iterator.hasNext() && item != currentItem; ) {
                  item = iterator.next() ;
                  total = total + item.getAmount() ;
                return total ;
            return value;
        final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
      // generics hell.. can't wait for lambdas...
      final Callback<TableColumn<LineItem, Number>, TableCell<LineItem, Number>> currencyCellFactory = new Callback<TableColumn<LineItem, Number>, TableCell<LineItem, Number>>() {
          @Override
          public TableCell<LineItem, Number> call(TableColumn<LineItem, Number> column) {
            return new TableCell<LineItem, Number>() {
              @Override
              public void updateItem(Number amount, boolean empty) {
                if (empty) {
                  setText(null) ;
                } else {
                  setText(currencyFormat.format(amount));
        amountCol.setCellFactory(currencyCellFactory);
        cumulativeAmountCol.setCellFactory(currencyCellFactory);
        BorderPane root = new BorderPane();
      root.setCenter(table);
      primaryStage.setScene(new Scene(root, 600, 400));
      primaryStage.show();
      public List<LineItem> createRandomData() {
        Random rng = new Random();
        List<LineItem> items = new ArrayList<>();
        for (int i=0; i<NUM_ITEMS; i++) {
          Calendar cal = Calendar.getInstance();
          cal.add(Calendar.DAY_OF_YEAR, rng.nextInt(365)-365);
          double amount = (rng.nextInt(90000)+10000)/100.0 ;
          items.add(new LineItem(cal.getTime(), amount));
        return items ;
      public static void main(String[] args) {
      launch(args);
    public static class LineItem {
        private final ObjectProperty<Date> date ;
        private final DoubleProperty amount ;
        public LineItem(Date date, double amount) {
          this.date = new SimpleObjectProperty<>(this, "date", date);
          this.amount = new SimpleDoubleProperty(this, "amount", amount);
        public final ObjectProperty<Date> dateProperty() {
          return date;
        public final Date getDate() {
          return date.get();
        public final void setDate(Date date) {
          this.date.set(date);
        public final DoubleProperty amountProperty() {
          return amount ;
        public final double getAmount() {
          return amount.get();
        public final void setAmount(double amount) {
          this.amount.set(amount);

  • Dynamic rows in TableView Iterator

    Hello All,
    I am developing an application in which there would be a TableView with last column as a button. OnClick event on the button should add the row below the current row (the facility should be like an Excel spreadsheet where we can insert the rows below). Can it be acheived by re-populating the internal table which his attached with TableView Control.
    Is it Ok to use TableView in such a condition or we have to go with pure HTML tables or some kind of ActiveX controls?
    Thanks in advance.
    Thanks And Regards
    Rajeev Patkie

    Hallo Rajeev,
    > Is it Ok to use TableView in such a condition...
    It is OK to use the tableView as long as it works for you! Once we run into problems, then of course one has to see if the functionality is "working as designed" and whether it was designed to handle your specific request.
    However, what you want to achieve sounds relatively harmless. Just use onclick on the button to trigger a server round trip. (Nice idea: write the row index directly into the onclick string!). Then add a new empty row into your at the correct index (see ABAP documentation), and just render table new.
    All of this should be relatively easy. Why don't you try, and let us see what you achieve.

  • Setting a data source for a tableView

    Greetings
    I'm trying to learn cocoa touch by following the Apple's code example called SQLiteBooks.
    there is a data source assignment within the MasterViewController code:
    - (void)loadView {
    tableView = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
    tableView.delegate = self;
    tableView.dataSource = self;
    self.view = tableView; }
    Can anybody explain how "tableView.dataSource = self" associates an NSArray "books", which actually has the data, with this tableView?
    Best regards,
    -Eugene

    I can give you a Cocoa-specific answer. Unfortunately, with the new iPhone SDK there are tons of new people posting questions about the iPhone. That is why I didn't respond yesterday. My answer may or may not make sense for the iPhone.
    When you setup a data source, the table view will call two methods on that data source to get data. It will call "numberOfRowsInTableView:" to get the number of data elements and "tableView:objectValueForTableColumn:row:" to get a specific value for a cell.
    Your data source should implement those methods and return data for the table view to dipslay.
    Full details are available in Apple's documentation

  • How to populate TableView data on the other screen TextField

    Hi guru’s
    I am having problem in populating data from a table in one screen to a Text Field in the other screen. I have two classes FirstClass containing a textbox and a button. On pressing a button a second window is opened containing a Table of values. As the user double clicks a row the value of the second column of the row should be inserted into the textbox of the FirstClass. Code of both the classes is attached. Thanking you in anticipation.
    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.GridPane;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    public class FirstClass extends Application {
    public static void main(String[] args) {
         launch(args);
    @Override
    public void start(final Stage primaryStage) {
         primaryStage.setTitle("First Class");
    GridPane gridpane = new GridPane();
              gridpane.setPadding(new Insets(5));
              gridpane.setHgap(5);
              gridpane.setVgap(5);
    final TextField userNameFld = new TextField();
    gridpane.add(userNameFld, 1, 1);
    Button btn = new Button();
    btn.setText("Show Table");
    gridpane.add(btn, 1, 3);
    btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
         String a = TableClass.showDialog(primaryStage, true, "Table Window" );
         userNameFld.setText(a);
    StackPane root = new StackPane();
    Scene scene =new Scene(root, 300, 250);
    root.getChildren().addAll(gridpane);
    primaryStage.setScene(scene);
    primaryStage.show();
    import javafx.beans.property.SimpleStringProperty;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.EventHandler;
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.GridPane;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Modality;
    import javafx.stage.Stage;
    public class TableClass extends Stage {
         private static TableClass dialog;
         private static String value = "";
         public static class Person {
    private final SimpleStringProperty firstName;
    private final SimpleStringProperty lastName;
    private Person(String fName, String lName) {
    this.firstName = new SimpleStringProperty(fName);
    this.lastName = new SimpleStringProperty(lName);
    public String getFirstName() {
    return firstName.get();
    public void setFirstName(String fName) {
    firstName.set(fName);
    public String getLastName() {
    return lastName.get();
    public void setLastName(String fName) {
    lastName.set(fName);
         private TableView<Person> table = new TableView<Person>();
         private final ObservableList<Person> data =
         FXCollections.observableArrayList(
         new Person("JACK", "BROWN"),
         new Person("JOHN", "VIANNEYS"),
         new Person("MICHAEL", "NELSON"),
         new Person("WILLIAM", " CAREY")
         public TableClass(Stage owner, boolean modality, String title) {
              super();
              initOwner(owner);
              Modality m = modality ? Modality.APPLICATION_MODAL : Modality.NONE;
              initModality(m);
              setOpacity(1);
              setTitle(title);
              StackPane root = new StackPane();
              Scene scene = new Scene(root, 750, 750);
              setScene(scene);
              GridPane gridpane = new GridPane();
              gridpane.setPadding(new Insets(5));
              gridpane.setHgap(5);
              gridpane.setVgap(5);
              TableColumn firstNameCol = new TableColumn("First Name");
         firstNameCol.setMinWidth(100);
         firstNameCol.setCellValueFactory(
         new PropertyValueFactory<Person,String>("firstName")
         TableColumn lastNameCol = new TableColumn("Last Name");
         lastNameCol.setMinWidth(200);
         lastNameCol.setCellValueFactory(
         new PropertyValueFactory<Person,String>("lastName")
         table.setItems(data);
         table.getColumns().addAll(firstNameCol, lastNameCol);
         table.setOnMouseClicked(new EventHandler<MouseEvent>() {
                   public void handle(MouseEvent me) {
                        if (me.getClickCount() >= 2) {
                   String srr = table.getItems().get(table.getSelectionModel().getSelectedIndex()).getLastName();
                   value = srr;
                   dialog.hide();
         gridpane.add(table, 1, 5,1,20 );
              root.getChildren().add(gridpane);
         public static String showDialog(Stage stg, Boolean a , String title){
              dialog = new TableClass( stg,a, title);
              dialog.show();
              return value;
    }

    Cross posted
    http://www.coderanch.com/t/582014/JavaFX/java/populate-TableView-data-other-screen
    http://stackoverflow.com/questions/10734649/how-to-populate-tableview-data-on-the-other-screen-textfield-in-javafx-2-0
    Moderator advice: Please read the announcement(s) at the top of the forum listings and the FAQ linked from every page. They are there for a purpose.
    Then edit your post and format the code correctly.
    db

Maybe you are looking for

  • Publishing project in HTML5 - video's don't work

    Hello, In my e-learning project I have implemented several video's as Event Video on a slide.  These video's work perfectly as I preview my project. But when I publish my project the video's don't seem to load.  Some video's show nothing (black scree

  • Blackmagic Intensity Pro Delay in AE

    This was not an issue for us prior to CC 2014, but now there is a delay in sync between the HDMI monitor and playback. When selecting monitor 2, there is no delay. Its only when going through the Blackmagic HDMI. In Premiere, there are delay settings

  • Is it possible to find the Equipment for given PP work center?

    Hello PM Masters, Is it possible to find the Equipment for given PP work center? Please tell me which table will lend me the EQUNR when I have the PP work center (ARBPL). Thank you.

  • Home Sharing source codes or properties ?

    Hello everyone, homesharing is using for sharing another computer. I thought that an android device is also a computer. so i want to find a way to use my itunes library on my android device. That way could be a program, or a service or something else

  • Logon Balancing error 88 and Error timeout occured for BW transaction Iview

    Hello All, I am trying to connect BW system from portal. We are using SAP GUI for Window to launch the Transaction iViews and browser we are using is IE 7.0 and IE 8.0. I have selected the Technique to Start SAP GUI for Windows is "SAP Shortcut File"