2

背景:

我有一个自定义 UIViewController 类,我在其中使用自定义注释填充 MKMapView。当用户选择注释时,会显示有关该注释的详细信息,并且还会出现一个按钮供用户选择并调出另一个 UIViewController,其中包含有关地图上该点的详细信息。

编码:

我通过创建具有 UserID 的类来初始化新的视图控制器(注意:- (id) initWithUserID:(NSInteger) userID;在 SecondViewController 的头文件中声明:

@interface SecondViewController ()

@property (nonatomic) NSInteger userID;

@end



@implementation RainFallDetailedViewController

@synthesize userID = _userID;


- (id) initWithUserID:(NSInteger) userID{

_userID = userID;
NSLOG(@"UserID: %i",self.userID); //correctly displays user id

return self;
}

- (void) viewWillAppear{
NSLOG(@"UserID: %i",self.userID); //userid is now 0

按下按钮时创建视图控制器,然后立即执行第二个视图控制器的 segue:

- (void)mapView:(MKMapView *)mapView 
annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {

if ([(UIButton*)control buttonType] == UIButtonTypeInfoLight){ //I'm looking for recognition of the correct button being pressed here.
    //SecondViewController is the second view controller with the detailed information about the map point.  
    //DataPoint is a custom class that contains the details regarding the map point.
    SecondViewController *detailedMapController = [[SecondViewController alloc] initWithUserID:((DataPoint *)view.annotation).userID]; 

    NSLOG(@"UserID: %i", ((DataPoint *)view.annotation).userID); //correctly displays userID

    [self performSegueWithIdentifier:@"PinDetail" sender:detailedMapController];


} 
}

问题:

使用 NSLOG 我能​​够确认在创建类时该值被正确传递。但是,当我userID稍后在代码 (viewWillAppear) 中使用该属性时,它不再可供我使用。我假设有一个我没有处理的内存问题,但我似乎无法弄清楚。如何确保在创建时传递给类的值/对象留在那里?

旁注:我最初尝试传递一个PinData对象,但遇到了同样的问题,所以我知道这不是 NSInteger 问题。我也遵循了 noa 的建议并使用prepareForSegue了,但是我遇到了上面提到的同样的问题

4

1 回答 1

3

segue 负责实例化控制器。不要实例化另一个——它只会被丢弃,这就是为什么属性值似乎不固定的原因。

要设置视图控制器,-prepareForSegue:请在父视图控制器中覆盖:

- (void) prepareForSegue:(UIStoryboardSegue *) segue sender:(id) sender {
    if ([segue.identifier isEqualToString:@"PinDetail"]) {
        SecondViewController *vc = segue.destinationViewController;
        vc.userID = self.userID;
    }
}

将上面的最后一段代码替换为:

self.userID = ((RainFallDataPoint *)view.annotation).userID;
[self performSegueWithIdentifier:@"PinDetail" sender:self];
于 2012-04-26T17:04:52.713 回答