gpt4 book ai didi

objective-c - 如果子类引用父类(super class) ivar,则合成不相关的属性会失败

转载 作者:IT王子 更新时间:2023-10-29 08:12:15 24 4
gpt4 key购买 nike

编辑: 我刚刚注意到另一个 Stack Overflow 问题问了同样的事情:Why does a subclass @property with no corresponding ivar hide superclass ivars?

这是一些有趣的行为,我无法在任何官方或非官方(博客、推文、SO 问题等)中找到记录。我已经将它归结为它的本质,并在一个新的 Xcode 项目中对其进行了测试,但我无法解释它。

MyBaseClass 有一个实例变量:

@interface MyBaseClass : NSObject {
NSObject *fooInstanceVar;
}
@end

MySubclass 扩展了 MyBaseClass,并声明了一个完全不相关的属性(即,该属性不打算由实例变量支持):

#import "MyBaseClass.h"
@interface MySubclass : MyBaseClass { }
@property (nonatomic, retain) NSObject *barProperty;
@end

如果 MySubclass 的实现合成属性但实现访问器方法,则一切都很好(没有编译器错误):

#import "MySubclass.h"
@implementation MySubclass

- (NSObject*)barProperty {
return [[NSObject alloc] init]; // pls ignore flagrant violation of memory rules.
}

- (void)setBarProperty:(NSObject *)obj { /* no-op */ }

- (void)doSomethingWithProperty {
NSArray *array = [NSArray arrayWithObjects:self.barProperty, fooInstanceVar, nil];
NSLog(@"%@", array);
}
@end

但如果我删除属性访问器方法并将它们替换为属性的 synthesize 声明,我会收到编译器错误:'fooInstanceVar' undeclared (first use in this function).

#import "MySubclass.h"
@implementation MySubclass
@synthesize barProperty;

- (void)doSomethingWithProperty {
NSArray *array = [NSArray arrayWithObjects:self.barProperty, fooInstanceVar, nil];
NSLog(@"%@", array);
}
@end

如果我删除 synthesize 声明,或者如果我不从 MySubclass.m 中引用 fooInstanceVar 实例变量,或者如果我将所有接口(interface)和实现定义在一个文件中。这个错误似乎也发生在 GCC 4.2 和 GCC/LLVM build设置中。

谁能解释一下这里发生了什么?

最佳答案

正如在这个问题中的回答:objective c xcode 4.0.2: subclass can't access superclass variables "was not declared in this scope"

来自文档:Apple Objective-C Programming Langage: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocDefiningClasses.html#//apple_ref/doc/uid/TP30001163-CH12-TPXREF125

The instance variable is accessible within the class that declares it and within classes that inherit it. All instance variables without an explicit scope directive have @protected scope.

However, a public instance variable can be accessed anywhere as if it were a field in a C structure. For example:

Worker *ceo = [[Worker alloc] init];

ceo->boss = nil;

我在使用 LLVM GCC 4.2 时遇到编译错误(对于 iOS 项目,在设备上):

error: 'fooInstanceVar' undeclared (first use in this function)and the same one using GCC 4.2 :error: 'fooInstanceVar' undeclared (first use in this function)

我可以使用 LLVM Compiler 2.0 编译而不会出错。

对于使用 self-> 的 LLVM GCC 4.2 和 GCC 4.2 进行编译:

[NSArray arrayWithObjects:self.barProperty, self->fooInstanceVar, nil];in the doSomethingWithProperty method.

关于objective-c - 如果子类引用父类(super class) ivar,则合成不相关的属性会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6822518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com