sách gpt4 ăn đã đi

Objective-C 对象 typedef 产生奇怪的 @encode 并破坏 KVC

In lại 作者:太空狗 更新时间:2023-10-30 03:33:26 28 4
mua khóa gpt4 giày nike

Hãy xem xét đoạn mã sau:

#import 
#import

typedef NSString* MyStringRef;
typedef NSString MyString;

@interface ClassA : NSObject
@property (nonatomic, copy) MyStringRef stringA;
@property (nonatomic, copy) MyString *stringB;
@kết thúc

@implementation ClassA
@synthesize stringA = _stringA;
@synthesize stringB = _stringB;
@kết thúc

int chính() {
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([ClassA class], &count);
for (unsigned int i = 0; i < count; i++) {
Ivar thisIvar = ivars[i];
NSLog(@"thisIvar = %s, %s", ivar_getName(thisIvar), ivar_getTypeEncoding(thisIvar));
}

ClassA *a = [[ClassA alloc] init];
NSLog(@"Out: %@", [a valueForKey:@"stringA"]);
NSLog(@"Out: %@", [a valueForKey:@"stringB"]);
}

这是输出:

$ clang --version
Apple clang version 3.1 (tags/Apple/clang-318.0.58) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin11.4.0
Thread model: posix

$ clang -o typedef -fobjc-arc -framework Foundation typedef.m && ./typedef
2012-06-06 20:14:15.881 typedef[37282:707] thisIvar = _stringA, @"NSString"
2012-06-06 20:14:15.884 typedef[37282:707] thisIvar = _stringB, ^{NSString=#}
2012-06-06 20:14:15.885 typedef[37282:707] Out: (null)
2012-06-06 20:14:15.888 typedef[37282:707] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key stringB.'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff835fef56 __exceptionPreprocess + 198
1 libobjc.A.dylib 0x00007fff878e5d5e objc_exception_throw + 43
2 CoreFoundation 0x00007fff836891b9 -[NSException raise] + 9
3 Foundation 0x00007fff83e77703 -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 240
4 Foundation 0x00007fff83dae38e _NSGetUsingKeyValueGetter + 108
5 Foundation 0x00007fff83dae315 -[NSObject(NSKeyValueCoding) valueForKey:] + 392
6 typedef 0x000000010e84bc6d main + 317
7 typedef 0x000000010e84b9c4 start + 52
)

我的问题是 Objective-C 是什么导致 typedef NSString MyString 有效地创建一个包含一个 Lớp học 类型变量的结构,然后在我使用 MyString 的地方使用它。例如结构看起来像这样(在咨询 cái này 之后):

struct NSString {
Class a;
};

这有点道理,但会导致 valueForKey: 失败,大概是因为它现在是一个结构,所以它不能以与对象相同的方式返回它。或者更准确地说,它属于搜索顺序described in the docs的“抛出异常”部分。 .

我只是想了解导致这种情况发生的语言是什么,以及为什么它不能以相同的方式处理我的 2 个 typedef。

câu trả lời hay nhất

我在 WWDC 2012 上得到了答案。事实证明,这种行为是预期的,因为与 GCC 的二进制兼容性也是如此。

对我来说似乎很奇怪,他们有效地引入了我认为是与旧 GCC 二进制兼容的错误。我希望这种事情最终会被淘汰,取而代之的是正确的编译器。

关于Objective-C 对象 typedef 产生奇怪的 @encode 并破坏 KVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10920781/

28 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress