【问题标题】:clarifying on properties in objective C澄清目标 C 中的属性
【发布时间】:2023-03-03 12:10:02
【问题描述】:

很抱歉这个简单的问题。
当我在h file 内看到一个属性的定义,但在@interface 类范围内 之外,这是什么意思?

@property (nonatomic, readonly) RMMapContents *mapContents;

代码如下:

@class RootViewController;
@class RMMapContents;

@interface MapTestbedAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;

    //MAIN VIEW
    //==============

    RootViewController *rootViewController;


    // NETWORK DATA
    // =============

    NSMutableArray  *photoTitles;         // Titles of images
    NSMutableArray  *photoSmallImageData; // Image data (thumbnail)
    NSMutableArray  *photoURLsLargeImage; // URL to larger image
    NSMutableData *receivedData;
    NSURLConnection *theConnection;
    NSURLRequest *request;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet RootViewController *rootViewController;
@property (nonatomic, readonly) RMMapContents *mapContents;


@end

在函数内部我看到这一行:

- (void)foo:(xyz *)abc{
  ..
  RMMapContents *mapContents = [self mapContents];
  ..
}

所以,从 C++ 中获取,mapContents 似乎不是全局范围的 var(毕竟,这就是他们称它们为属性的原因,对吧?),但在函数内部没有再次定义相同的名称有点奇怪?

我希望有人可以在这里澄清一点。
谢谢!

【问题讨论】:

  • 你确定@property 是在@interface 部分之外声明的吗,因为如果我这样做会产生编译错误。
  • 超出范围是什么意思?在你的问题中给出你对接口的所有定义。

标签: iphone objective-c ios properties


【解决方案1】:

@interface 块的范围延伸到@end 关键字,并且不限于大括号{}。

所以@property 声明非常位于@interface 的范围内,就像 cli_hlt 正确回答一样,它就像 mapContents 属性的 setter 和 getter 方法的替代品。

所以一个名为 mapContents 的属性将具有如下所示的 setter 和 getter:

- (void)setMapContents; //setter

- (RMMapContents *)mapContents; //getter

并且可以使用这些方法从类中访问:

[self setMapContents:newContents];

RMMapContents *contents = [self mapContents];

【讨论】:

    【解决方案2】:

    嗯,属性不仅仅是一个变量。属性是一个变量加上它的 setter 和 getter 方法。属性通常被称为由变量支持,该变量通常(但不总是)与属性本身具有相同的名称。

    所以基本上有三种情况:

    1. 开发者重新定义了后备变量,在实现的开始处寻找类似:@synthesize mapContents=mapContents_的东西->这里没问题。

    2. 编译器将变量定义为您现在没有但不等于mapContents -> 没问题。

    3. 属性支持变量确实称为“mapContents”,因此本地定义隐藏了全局定义(在此处查找编译器警告)。但是通过调用[self mapContents],您将不会访问全局变量,而是调用getter,后者又会访问类变量(因为此时本地mapContents 超出范围)

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      global var mapContents 是只读的,在 foo 函数中,创建一个新的指针,然后你可以改变内部 var 的值。

      【讨论】:

        【解决方案4】:

        在您的类中查找名称为 mapContents 的方法,该方法将初始化您的 RMMapContents 类。

        基本上这行RMMapContents *mapContents = [self mapContents]; 表示使用mapContents 方法初始化一个名为mapContensRMMapContents 实例。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-12
          • 1970-01-01
          • 1970-01-01
          • 2014-07-21
          相关资源
          最近更新 更多