Steaphann
Steaphann

Reputation: 2777

passing an Int from one ViewController to another using a segue

I am trying to pass an int from one VC to another. I am doing it like this.

In my VC1 I am doing a segueshowDetail when I call the prepareForSegue method. It looks like this.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSIndexPath *indexPath = (NSIndexPath *)sender;
    News *news = [arrNews objectAtIndex:indexPath.row];
    NSLog(@"news id is %@",news.new_id);
    if ([segue.identifier isEqualToString:@"showDetail"]) {
        [segue.destinationViewController setNewsId:(int)news.new_id];
    }
}

In the Log I get the correct number back. Now in my VC2 I have declared an int like this.

@property (nonatomic) int newsId;

And my setMethod looks like this.

-(void)setNewsId:(int)newsId{
    NSLog(@"news id is %d",newsId);
    self.newsId = newsId;

}

When I executed I come in a loop with all big numbers. Can someone help me with this problem?

Upvotes: 0

Views: 888

Answers (2)

Mark Kryzhanouski
Mark Kryzhanouski

Reputation: 7241

This code couse to loop:

-(void)setNewsId:(int)newsId{
    NSLog(@"news id is %d",newsId);
    self.newsId = newsId;
}

And should be:

-(void)setNewsId:(int)newsId{
    NSLog(@"news id is %d",newsId);
    _newsId = newsId;
}

Where _newsId is ivar.

UPD Seems that news.new_id has NSNumber type. So extract integer value

[segue.destinationViewController setNewsId:[news.new_id integerValue]];

Upvotes: 7

Anil Varghese
Anil Varghese

Reputation: 42977

self.newsId = newsId; This will call your setter method setNewsId:. It causes an infinite loop. Always access the instance variable directly inside the setter and getter.

_newsId = newsId;

Your actual problem is '(int)news.new_id' this casting. This giving you wrong value try to put a log for this value. I hop news.new_id is a NSNumber then either make the property as NSNumber type or if you want int only take [news.new_id intValue] and set. Do not type cast.

Upvotes: 1

Related Questions