代码之家  ›  专栏  ›  技术社区  ›  Ben Baron

nib文件中的对象与代码中的IBOutlet对象不关联

  •  0
  • Ben Baron  · 技术社区  · 14 年前

    下面是这样的情况:我有一个带有XIB文件的UIViewController。它有一个连接到view属性的UIView,一个连接到名为imageView的属性的UIImageView,以及一个连接到segmentControl的UISegmentedControl。

    但在我的代码中,我无法将图像分配给图像视图。当我NSLog对象时,我得到的地址是0x0,所以它根本没有关联。我在Interface builder中设置了绑定,重新启动XCode并清理和构建项目。什么都不管用,我浪费了大量的时间试图解决这个问题。我还对segmentControl对象进行了nslogg,得到了0x0。因此,XIB中没有任何东西与代码连接,但是XIB本身正在加载,因为对象显示在屏幕上。

    有人知道我会错过什么吗?这是一件很简单的事情,它突然拒绝工作让人难以置信的沮丧。


    下面是代码,在本例中,我正在为projectId访问setter中的对象,但我也尝试从另一个类访问imageView,但它也不起作用(是的,我尝试时有一个@property声明并为imageView进行合成)。

    图表视图控制器.h:

    #import <UIKit/UIKit.h>
    
    
    @interface DiagramViewController : UIViewController 
    {
        NSUInteger projectId;
        IBOutlet UIImageView *imageView;
        IBOutlet UISegmentedControl *segmentControl;
    }
    
    @property NSUInteger projectId;
    
    @end
    

    图表视图控制器.m:

    #import "DiagramViewController.h"
    
    @implementation DiagramViewController
    @synthesize projectId;
    
    -(void)setProjectId:(NSUInteger)projId
    {
        NSLog(@"imageView: %@", imageView);
        NSLog(@"segmentControl: %@", segmentControl);
    
        projectId = projId;
    
        NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%i_schem", projectId] ofType:@"png" inDirectory:@"project-details/images/diagrams"];
        NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    
        imageView.image = [UIImage imageWithData:imageData];
    }
    
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
        // Overriden to allow any orientation.
        return YES;
    }
    
    - (void)didReceiveMemoryWarning {
        // Releases the view if it doesn't have a superview.
        [super didReceiveMemoryWarning];
    
        // Release any cached data, images, etc that aren't in use.
    }
    
    - (void)viewDidUnload {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
    }
    
    - (void)dealloc {
        [super dealloc];
    }
    
    @end
    

    以下是界面生成器连接的图像: http://i52.tinypic.com/2eakprl.png

    2 回复  |  直到 14 年前
        1
  •  3
  •   d11wtq Vadim Baryshev    14 年前

    你要确保你在 -viewDidLoad 方法,否则nib文件实际上并没有取消对象的归档,因此它们将被设置为nil。尤其是,在 -init 方法。

    编辑:好的,谢谢你发布代码。什么时候 -setProjectId: 被调用?你确定笔尖已经在这一点上装好了吗?你没有 viewDidLoad 方法,因此看起来您在任何时候都不会检查它。

    http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html

    视图加载

    在控制器视图加载到内存中后调用。

    讨论

    此方法在视图控制器将其关联视图加载到内存中后调用。无论视图是存储在nib文件中还是以编程方式在loadView方法中创建,都会调用此方法。此方法最常用于对从nib文件加载的视图执行附加的初始化步骤。

        2
  •  0
  •   nicktmro    14 年前

    在IB中,右键单击 UISegmentedControl 然后贴一张截图让我们看看你有什么。如果你看到任何黄色的东西,那么你可能已经发现了你的问题。