iOS在Nib中使用外部对象

时间:2010-09-14 00:53:02

标签: iphone objective-c xcode cocoa-touch interface-builder

我正在编写一个需要与不同后端系统接口的应用程序。我决定使用一个协议来抽象我的后端类。我创建了一个名为LoginViewController的nib,其中包含“NSObject”类型的“外部对象”引用,并将其连接到我的LoginViewController中的systemDelegate出口。

@interface LoginViewController : UIViewController {

}

@property (nonatomic, retain) IBOutlet UITextField *usernameTextView;
@property (nonatomic, retain) IBOutlet UIImageView *captchaImageView;
@property (nonatomic, retain) IBOutlet UITextField *captchaTextView;
@property (nonatomic, retain) IBOutlet NSObject <BackEndSystemDelegate> *systemDelegate;

- (IBAction) submitCaptcha:(id) sender;
- (IBAction)dismissKeyboard: (id)sender;
- (IBAction) animateViewUp: (id) sender;
- (IBAction) animateViewDown: (id) sender;
- (void) animateViewOnYAxis: (int) offset;
- (void) loadCaptchaImage;

@end

我在我的应用程序委托中实现了LoginViewController,然后尝试使用外部对象引用加载nib。我的代码调用loadNibNamed并在没有堆栈跟踪的情况下崩溃。调用后我没有到达NSLog语句:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    NSObject <BackEndSystemDelegate> *systemDelegate = [[ACMEBackEndSystemDelegate alloc] init];


    // Init LoginView, and load nib with systemDelegate
    self.viewController = [[LoginViewController alloc] init];
    NSDictionary *proxies = [NSDictionary dictionaryWithObject:systemDelegate forKey:@"systemDelegate"];
    NSDictionary *options = [NSDictionary dictionaryWithObject:proxies forKey:UINibExternalObjects];

    NSArray *toplevelobjects = [[NSBundle mainBundle] loadNibNamed:@"LoginViewController" 
                                                             owner:self.viewController 
                                                           options:options];

    if (toplevelobjects) {
        NSLog(@"toplevelobjects is nil");
    } else {
        NSLog(@"toplevelobjects count %d", [toplevelobjects count]);
    }


    NSLog(@"Controller: %@, View: %@", viewController, viewController.view);

    // Add the view controller's view to the window and display.
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];

    return YES;
}

我无法想象这一点。任何帮助将不胜感激。

谢谢, J加西亚

1 个答案:

答案 0 :(得分:2)

一些评论:

  • 通常,您使用模式id<SomeProtocolName>而不是NSObject<SomeProtocolName>

  • 来引用委托对象
  • alloc systemDelegate变量但从未release变量。这是内存泄漏。

  • 如果ACMEBackEndSystemDelegate类实现了BackEndSystemDelegate协议,则可以像ACMEBackEndSystemDelegate* systemDelegate = [[ACMEBackEndSystemDelegate alloc] init];

  • 那样分配它。

现在,关于你的崩溃,你说这条线上有一个崩溃:

NSArray *toplevelobjects = [[NSBundle mainBundle] loadNibNamed:@"LoginViewController" 
                                                             owner:self.viewController 
                                                           options:options];

我假设您有一个名为LoginViewController.xib的.xib。打开它。那是为“文件所有者”设置的类类型?是LoginViewController吗?如果没有,请设置它。现在查看view outlet属性。它是否设置为.xib中的UIView(可能是顶级UIView对象)?如果没有,请设置它。