How to pass variable from uitableview to second tableview using didSelectRowAtIndexPath? - xcode

i want to pass the variable from a view controller to another one, so that when the user selects a certain row in the first table view, the application will take him to another view controller in which the details of the selected item will appear.
This is my code :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *selectedAuthors = [theauthors objectAtIndex:indexPath.row];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
Details *dvController = [storyboard instantiateViewControllerWithIdentifier:#"Details"]; //Or whatever identifier you have defined in your storyboard
dvController.selectedAuthors = selectedAuthors;
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:authorNAme delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
// Display Alert Message
authorNAme = [[NSString stringWithFormat:[theauthors objectAtIndex:indexPath.row]] intValue];
[messageAlert show];
[self.navigationController pushViewController:dvController animated:YES];
}
selectedAuthors is a string
authorName is a global variable in which i want to store the content of the selected row.
Any help will be highly appreciated.

I see you are using storyboards.
In this case, to send information to the next view controller you have to implement
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
This method gets called every time a segue is about to be performed.
For instance, in didSelectRowAtIndexPath you can save the row's information in a dictionnary and pass it to the next view controller in the prepareForSegue method.
For detailed information you can check out Apple's sample project named SimpleDrillDown. It does the same thing you need to do:
http://developer.apple.com/library/ios/#samplecode/SimpleDrillDown/Introduction/Intro.html

NSString *titleString = [[[NSString alloc] initWithFormat:#"Element number : %d",indexPath.row] autorelease];
This is the simplest function used to send variables and it just came out of nowhere! For anyone lost this is the best function!!

Related

Passing NSMutableArray with modal view

I have 2 views, in the second one I initialize a NSMutableArray and I want to pass it back to the first View. In the second view I have a button connected with the following action:
-(IBAction)back:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil]
}
With this action I go back from my second ViewController to the first ViewController, is there a way to pass the NSMutableArray from that action?
If you are not using prepareForSegue then you can user NSUserDefaults:
-(IBAction)back:(id)sender {
NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
[[NSUserDefaults standardUserDefaults]setObject:mutableArray forKey:#"array"];
[self dismissViewControllerAnimated:YES completion:nil];
//I'm guessing you are going to load the viewController that's up next?
}
You can retrieve it in the viewDidLoad like so:
// to retrieve in maybe viewDidLoad?
NSArray * array = [[NSUserDefaults standardUserDefaults]arrayForKey:#"array"];
NSMutableArray *mutableArray = [array mutableCopy];

NSPopupButton in view based NSTableView: getting bindings to work

Problem Description
I'm trying to achieve something that should be simple and fairly common: having a bindings populated NSPopupButton inside bindings populated NSTableView. Apple describes this for a cell based table in the their documentation Implementing To-One Relationships Using Pop-Up Menus and it looks like this:
I can't get this to work for a view based table. The "Author" popup won't populate itself no matter what I do.
I have two array controllers, one for the items in the table (Items) and one for the authors (Authors), both associated with the respective entities in my core data model. I bind the NSManagedPopup in my cell as follows in interface builder:
Content -> Authors (Controller Key: arrangedObjects)
Content Values -> Authors (Controller Key: arrangedObjects, Model Key Path: name)
Selected Object -> Table Cell View (Model Key Path: objectValue.author
If I place the popup somewhere outside the table it works fine (except for the selection obviously), so I guess the binding setup should be ok.
Things I Have Already Tried
Someone suggested a workaround using an IBOutlet property to the Authors array controller but this doesn't seem to work for me either.
In another SO question it was suggested to subclass NSTableCellView and establish the required connections programmatically. I tried this but had only limited success.
If I setup the bindings as follows:
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
NSView *view = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];
if ([tableColumn.identifier isEqualToString:#"Author") {
AuthorSelectorCell *authorSelectorCell = (AuthorSelectorCell *)view;
[authorSelectorCell.popupButton bind:NSContentBinding toObject:self.authors withKeyPath:#"arrangedObjects" options:nil];
[authorSelectorCell.popupButton bind:NSContentValuesBinding toObject:self.authors withKeyPath:#"arrangedObjects.name" options:nil];
[authorSelectorCell.popupButton bind:NSSelectedObjectBinding toObject:view withKeyPath:#"objectValue.author" options:nil];
}
return view;
}
the popup does show the list of possible authors but the current selection always shows as "No Value". If I add
[authorSelectorCell.popupButton bind:NSSelectedValueBinding toObject:view withKeyPath:#"objectValue.author.name" options:nil];
the current selection is completely empty. The only way to make the current selection show up is by setting
[authorSelectorCell.popupButton bind:NSSelectedObjectBinding toObject:view withKeyPath:#"objectValue.author.name" options:nil];
which will break as soon as I select a different author since it will try to assign an NSString* to an Author* property.
Any Ideas?
I had the same problem. I've put a sample project showing this is possible on Github.
Someone suggested a workaround using an IBOutlet property to the Authors
array controller but this doesn't seem to work for me either.
This is the approach that did work for me, and that is demonstrated in the sample project. The missing bit of the puzzle is that that IBOutlet to the array controller needs to be in the class that provides the TableView's delegate.
Had the same problem and found this workaround - basically get your authors array controller out of nib with a IBOutlet and bind to it via file owner.
You can try this FOUR + 1 settings for NSPopUpbutton:
In my example, "allPersons" is equivalent to your "Authors".
I have allPersons available as a property (NSArray*) in File's owner.
Additionally, I bound the tableView delegate to File's owner. If this is not bound, I just get a default list :Item1, Item2, Item3
I always prefer the programmatic approach. Create a category on NSTableCellView:
+(instancetype)tableCellPopUpButton:(NSPopUpButton **)popUpButton
identifier:(NSString *)identifier
arrayController:(id)arrayController
relationship:(NSString *)relationshipName
relationshipArrayController:(NSArrayController *)relationshipArrayController
relationshipAttribute:(NSString *)relationshipAttribute
relationshipAttributeIsScalar:(BOOL)relationshipAttributeIsScalar
valueTransformers:(NSDictionary *)valueTransformers
{
NSTableCellView *newInstance = [[self alloc] init];
newInstance.identifier = identifier;
NSPopUpButton *aPopUpButton = [[NSPopUpButton alloc] init];
aPopUpButton.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
[aPopUpButton bind:NSContentBinding //the collection of objects in the pop-up
toObject:relationshipArrayController
withKeyPath:#"arrangedObjects"
options:nil];
NSMutableDictionary *contentBindingOptions = [NSMutableDictionary dictionaryWithDictionary:[[TBBindingOptions class] contentBindingOptionsWithRelationshipName:relationshipName]];
NSValueTransformer *aTransformer = [valueTransformers objectForKey:NSValueTransformerNameBindingOption];
if (aTransformer) {
[contentBindingOptions setObject:aTransformer forKey:NSValueTransformerNameBindingOption];
}
[aPopUpButton bind:NSContentValuesBinding // the labels of the objects in the pop-up
toObject:relationshipArrayController
withKeyPath:[NSString stringWithFormat:#"arrangedObjects.%#", relationshipAttribute]
options:[self contentBindingOptionsWithRelationshipName:relationshipName]];
NSMutableDictionary *valueBindingOptions = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSAllowsEditingMultipleValuesSelectionBindingOption,
[NSNumber numberWithBool:YES], NSConditionallySetsEditableBindingOption,
[NSNumber numberWithBool:YES], NSCreatesSortDescriptorBindingOption,
[NSNumber numberWithBool:YES], NSRaisesForNotApplicableKeysBindingOption,
[NSNumber numberWithBool:YES], NSValidatesImmediatelyBindingOption,
nil];;
#try {
// The object that the pop-up should use as the selected item
if (relationshipAttributeIsScalar) {
[aPopUpButton bind:NSSelectedValueBinding
toObject:newInstance
withKeyPath:[NSString stringWithFormat:#"objectValue.%#", relationshipName]
options:valueBindingOptions];
} else {
[aPopUpButton bind:NSSelectedObjectBinding
toObject:newInstance
withKeyPath:[NSString stringWithFormat:#"objectValue.%#", relationshipName]
options:valueBindingOptions];
}
}
#catch (NSException *exception) {
//NSLog(#"%# %# %#", [self class], NSStringFromSelector(_cmd), exception);
}
#finally {
[newInstance addSubview:aPopUpButton];
if (popUpButton != NULL) *popUpButton = aPopUpButton;
}
return newInstance;
}
+ (NSDictionary *)contentBindingOptionsWithRelationshipName:(NSString *)relationshipNameOrEmptyString
{
NSString *nullPlaceholder;
if([relationshipNameOrEmptyString isEqualToString:#""])
nullPlaceholder = NSLocalizedString(#"(No value)", nil);
else {
NSString *formattedPlaceholder = [NSString stringWithFormat:#"(No %#)", relationshipNameOrEmptyString];
nullPlaceholder = NSLocalizedString(formattedPlaceholder,
nil);
}
return [NSDictionary dictionaryWithObjectsAndKeys:
nullPlaceholder, NSNullPlaceholderBindingOption,
[NSNumber numberWithBool:YES], NSInsertsNullPlaceholderBindingOption,
[NSNumber numberWithBool:YES], NSRaisesForNotApplicableKeysBindingOption,
nil];
}

Xcode and alertview with view controller

What i am trying to achieve is go to another view when my alert view button is clicked. My alert view is inside my loadingView, this alert view is called from another class called classA.
This is how it is called in classA.
[LoadingViewController showError];
This is the method in loadingView in loadingView class.
+ (void)showDestinationError{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Error"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
alert.tag = DEST_ERR;
[alert show];
}
Button action
+ (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(alertView.tag = DEST_ERR){
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard_iPhone" bundle:[NSBundle mainBundle]];
UINavigationController *secondView = [storyboard instantiateViewControllerWithIdentifier:#"NavigationController"];
secondView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[secondView presentModalViewController:secondView animated:YES];
}
}
This gives me an error. 'Application tried to present modal view controller on itself. Presenting controller is UINavigationController:..
Note: my method is a '+'
The problem is this line:
[secondView presentModalViewController:secondView animated:YES];
A view controller can't present itself, and in this case doesn't even exist yet).
The most obvious way to fix this is to make your clickedButtonAtIndex an instance method since it needs to access information about the particular instance. You would then use this:
[self presentModalViewController:secondView animated:YES];
Otherwise, you need to get a reference to a view which can present your view controller. There are various ways to do this depending on how your app is setup which could include getting it from your app delegate or referencing the app window.

mwfeedpaser detailview

I just started using xcode and OBJ-c this year.
I am using mwfeedparser for a app I'm making but would like to change the look of the detailview.
right now i'm using the demo app that came with mwfeedparser to change the detail view.
i would like the detail view to have labels instead of being a tableview
i have changed this code
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detail = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:nil];
detail.item = (MWFeedItem *)[itemsToDisplay objectAtIndex:indexPath.row];
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detail animated:YES];
// Deselect
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
when i run the code the detailview doesn't even come up. am I doing something wrong?
thanks for your help.
btw when i do get this done I'll put it up on github incase anybody else needs it
enter code hereself.parsedItems = [[NSMutableArray alloc] init];
- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item{
if (item) {
[self.parsedItems addObject:item];
}
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailViewController *detail = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:nil];
detail.item = [self.parsedItems objectAtIndex:indexPath.row];
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detail animated:YES];
}

How to update detailView using a popover

I have a TableViewController which is represented by a popover, that is displayed by selecting a bar button item on a tool bar. I'm having a problem however that when I select an item from the table in the popover it doesn't update the view (affirmaPDFViewController)
Here is the DidSelectRowAtIndex method for my PDFTableController (the popover):
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
affirmaPDFViewController.detailItem = [NSString stringWithFormat:#"%#", [listOfPDF objectAtIndex:indexPath.row]];
affirmaPDFViewController.i = indexPath.row;
NSLog(#"%d", indexPath.row);
NSLog(#"%#", [listOfPDF objectAtIndex:indexPath.row]);
NSLog(#"%d", affirmaPDFViewController.i);
NSLog(#"%#", affirmaPDFViewController.detailItem);
}
Here the indexPath.row and the objectAtIndex:indexPath.row all return the correct values. However when I assign the variables from affirmaPDFViewController to those values they just return 0 and null.
I've been told it is because I haven't created an instance of affirmaPDFViewController. However, I'm not sure how to create such an instance. What code would I put in this method to get this to work?
Thanks in advance!
- (void)viewDidLoad
{
[super viewDidLoad];
affirmaPDFViewController = [[NameOfClassGoesHere alloc] initWithNibName:#"NibNameGoesHere" bundle:nil];
}

Resources