0

I am using the following to create a reference to a view controller in my code like this:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  if([segue.identifier isEqualToString:@"detailSegue"]){
    NSIndexPath *indexPath=[self.tableView indexPathForSelectedRow];
    TRDetailViewController *vc=segue.destinationViewController;
    vc.item=self.items[indexPath.row];
    [vc setValue:self forKeyPath:@"delegate"];
    [vc setValue:indexPath.row forKeyPath:@"itemIndex"];
  }
}

and this is declared as in TRDetailViewController

@interface TRDetailViewController : UIViewController
  @property (weak, nonatomic) IBOutlet UILabel *detailLabel;
  @property NSString *item;
  @property (nonatomic, weak)id delegate;
  @property NSInteger itemIndex;
  - (IBAction)deleteItem:(id)sender;
@end

but I get the following error

enter image description here

and I'm not sure why. I am trying to pass the location in an index of the cell selected in a UITableView. If a better way, please let me know. Why am I getting this error?

thx

geraldWilliam
  • 4,123
  • 1
  • 23
  • 35
timpone
  • 19,235
  • 36
  • 121
  • 211
  • thx for edit - had someone talking to me – timpone Jun 19 '13 at 23:52
  • Sure! FWIW, i find that I make fewer errors when I prefer objective-c properties to key-value coding. For instance, if you've imported a class and you try to assign a value to a property on that class that is not visible, the compiler lets you know. You don't get that when using the literal string keyPaths that setValue:forKeyPath: takes. – geraldWilliam Jun 19 '13 at 23:57

2 Answers2

1

setValue:forKeyPath: requires an object (i.e. id) as first argument.

You are instead passing a NSInteger.

You will have to use an object type, which means to turn your itemIndex into a NSNumber.

Then you can store it using

[vc setValue:@(indexPath.row) forKeyPath:@"itemIndex"];

and retrieve it by

NSInteger myIndex = [vc valueForKey:@"itemIndex"].integerValue;
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
1

setValue:forKey: is expecting an object for its value argument and you are passing it a primitive (in this case, an integer). You can work around this by amending your method to read as follows:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  if([segue.identifier isEqualToString:@"detailSegue"]){
    NSIndexPath *indexPath=[self.tableView indexPathForSelectedRow];
    TRDetailViewController *vc=segue.destinationViewController;
    vc.item=self.items[indexPath.row];
    [vc setValue:self forKeyPath:@"delegate"];
    [vc setValue:[NSNumber numberWithInt:indexPath.row] forKeyPath:@"itemIndex"];
  }
}

And then access it like:

[[vc valueForKey:@"itemIndex"] intValue];
geraldWilliam
  • 4,123
  • 1
  • 23
  • 35