objective-c - cocoa-为什么有一个 IBOutlet 和一个同名的属性?

标签 objective-c macos cocoa

我是 Objective-c 的新手。当我阅读别人写的一些源代码时,遇到了一个问题。

我发现有

    IBOutlet NSPopover *popover;

以及

@property NSPopover *popover;

PopoverViewController.h

#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import "TimerPopoverViewController.h"

@class TimerLogic;
@class TimerInfo;

@interface TimerPopoverDelegate : NSObject <NSPopoverDelegate> {
@private
    IBOutlet NSPopover *popover;
    IBOutlet NSWindow *detachWindow;
    IBOutlet TimerPopoverViewController *viewController;
}

@property NSPopover *popover;

- (void)showPopover:(id)sender timerInfo:(TimerInfo *)timerInfo;

@end

我认为它们是不同的变量。但是,我不明白他们是做什么的?

就我而言,IBOutlet 用于显示弹出窗口。 但是 @property 的作用是什么?

最佳答案

这要么是非常古老的代码,要么是用非常古老(现在不鼓励)的风格编写的。这里的IBOutlet声明了一个实例变量(ivar)。 @property 声明一个由实例变量支持的属性。在现代 ObjC 中,你应该这样实现它:

PopoverViewController.h

#import <Cocoa/Cocoa.h>

@class TimerInfo;

// Things declared here are public
@interface TimerPopoverDelegate : NSObject <NSPopoverDelegate>

// You could leave this here if it is required by other parts of the program,
// but other parts of the program really shouldn't require it. See below.
// @property (nonatomic, readonly, weak) NSPopover *popover;

- (void)showPopover:(id)sender timerInfo:(TimerInfo *)timerInfo;

@end

PopoverViewController.m

// Generally avoid importing local headers into the .h unless you have to.
#import "TimerPopoverViewController.h"

// Things declared here are private. This is much better than the old @private.
@interface TimerPopoverDelegate ()
@property (nonatomic, readwrite, weak) IBOutlet NSPopover *popover;
@property (nonatomic, readwrite, weak) IBOutlet NSWindow *detachWindow;
@property (nonatomic, readwrite, weak) IBOutlet TimerPopoverViewController *viewController;
@end

(当前 popover 是公共(public)的,但您应该避免以这种方式公开 IBOutlet。外部对象不应直接接触 View Controller 的导出。)

关于objective-c - cocoa-为什么有一个 IBOutlet 和一个同名的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36157287/

相关文章:

Objective-C 或 Cocoa First

ios - 如何将 NSDecimalNumber 除以整数?

macos - [NSApplication _crashOnExeption] 崩溃

ios - UITextView 行间距导致段落行之间的光标高度不同

macos - 在到达应用程序之前调试 OS X 中的关键事件流

database - SQLite 安全选项我需要加密数据库吗?

ruby - 在 OS X 上使用 Homebrew 还是 ruby​​ 版本管理器?

ios - 如果字符串的长度大于标签中显示的行数,如何使添加在 UILabel 中看到更多功能?

ios - 在 ViewController 之前编译的自定义类

ios - 在 ios 8 上使用 xib 抛出异常的自定义表格单元格 View