gpt4 book ai didi

objective-c - 在 Cocoa 中定义自己的关键路径运算符

转载 作者:太空狗 更新时间:2023-10-30 03:18:08 24 4
gpt4 key购买 nike

是否可以定义自己的关键路径运算符,例如@avg、@sum 等……

最佳答案

简答:有点。您可以重写 valueForKeyPath: 以拦截您的自定义运算符或转发到 super,但这可能会有问题(我将把对此的解释作为练习留给读者).

长答案:是的,你可以,但它依赖于使用私有(private)行为(而不是私有(private) api)。

在对 NSArray 进行一些简洁的自省(introspection)之后,我发现了一些私有(private)方法:

_distinctUnionOfSetsForKeyPath:
_distinctUnionOfObjectsForKeyPath:
_distinctUnionOfArraysForKeyPath:
_unionOfSetsForKeyPath:
_unionOfArraysForKeyPath:
_unionOfObjectsForKeyPath:
_minForKeyPath:
_maxForKeyPath:
_countForKeyPath:
_avgForKeyPath:
_sumForKeyPath:

好吧,整洁!这些方法似乎与可用于集合的运算符匹配:@sum@min@max@distinctUnionOfObjects 等。@ 已替换为下划线,并且我们附加了 ForKeyPath:

所以看起来我们可以创建一个新方法来匹配适当的签名,我们很高兴。

所以:

@interface NSArray (CustomOperator)

- (id) _fooForKeyPath:(NSString *)keyPath;

@end

@implementation NSArray (CustomOperator)

- (id) _fooForKeyPath:(NSString *)keyPath {
//keyPath will be what comes after the keyPath. In this example, it will be "self"
return @"Hello world!";
}

@end

NSArray * array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
NSLog(@"%@", [array valueForKeyPath:@"@foo.SELF"]); //logs "Hello world!"

它有效,但我不确定我是否会依赖它,因为它依赖于将来可能会改变的实现细节。

关于objective-c - 在 Cocoa 中定义自己的关键路径运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4100458/

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