OGeek|极客世界-中国程序员成长平台

标题: objective-c - 为什么不定义 UIWindow *_window 就可以访问 _window? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 18:21
标题: objective-c - 为什么不定义 UIWindow *_window 就可以访问 _window?

这是一个后续问题:Why rename synthesized properties in iOS with leading underscores?

MyDelegate.h

#import <UIKit/UIKit.h>

@interface MyAppDelegate

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) MyMainViewController *mainViewController;

@end

MyDelegate.m

#import "MyAppDelegate.h"

@implementation MyAppDelegate

@synthesize window = _window;
@synthesize mainViewController = _mainViewController;

除了 original question 中解释的内容外关于 _ 前缀的好处,我想知道为什么 _window 是可访问的

@synthesize window = _window;

在第一次使用之前没有在任何地方定义?



Best Answer-推荐答案


这既是声明又是定义。 @synthesize 指令能够创建访问器方法和实例变量。来自 TOCPL,"Declared Properties: Property Implementation Directives" :

You can use the form property=ivar to indicate that a particular instance variable should be used for the property...
For the modern runtimes (see “Runtime Versions and Platforms” in Objective-C Runtime Programming Guide), instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used.

所以如果你已经有一个 ivar 的声明,

@interface MyAppDelegate : NSObject
{
    NSWindow * _window;
}

将被使用(这在“旧版”平台中是必需的)。否则,它由 @synthesize 指令创建。在任何一种情况下,类中的结果都是相同的,尽管应该注意,合成变量的创建就像它们是用 @private 指令声明的一样;子类可以访问该属性,但不能直接访问 ivar。在独一无二的 Cocoa With Love 进行更多调查:Dynamic ivars: solving a fragile base class problem .

关于objective-c - 为什么不定义 UIWindow *_window 就可以访问 _window?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8322936/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4