【问题标题】:Setting up a detail view controller using a segue使用 segue 设置详细视图控制器
【发布时间】:2012-04-26 16:55:33
【问题描述】:

背景:

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

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

【问题讨论】:

    标签: objective-c object memory-management ios5


    【解决方案1】:

    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];
    

    【讨论】:

    • 好吧,你实例化的视图控制器几乎肯定不是正在显示的视图控制器,这可能是为什么属性值似乎没有固定的原因。不要实例化另一个视图控制器作为发送者传递,只需传递 selfmapView
    • 但是我如何将正确的用户 ID 与新的 viewController 关联起来。另外,这不会像原来的那样创建另一个视图控制器吗?
    • 我刚刚检查过了。将 self 作为发件人传递给我同样的问题。
    • 看起来你应该通过覆盖prepareForSegue:来做到这一点。
    • 使用 presentViewController 只会出现黑屏:/
    猜你喜欢
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2013-05-09
    相关资源
    最近更新 更多