gpt4 book ai didi

objective-c - someArray[5] 为什么以及如何在 objective-c 中工作?

转载 作者:搜寻专家 更新时间:2023-10-30 20:00:35 26 4
gpt4 key购买 nike

我认为新符号是这样工作的:

someArray[5] 变成

someArray[5] 实际上会变成 [someArray objectAtIndexedSubscript:5]

但是,在 NSArray.h 和 NSOrderedSet.h 中我看到了这个:

- (id)objectAtIndexedSubscript:(NSUInteger)idx NS_AVAILABLE(10_8, 6_0);

因此,objectAtIndexedSubscript 仅适用于 IOS6。

我尝试制作这个简单的代码:

NSArray * someArray =@[@"hello",@"World",@"World"];
NSOrderedSet * someOS = [NSOrderedSet orderedSetWithArray:someArray];
PO(someArray);
PO(someOS);
PO(someArray[0]);
PO(someOS[0]); //Exception thrown here

代码在 someOS[0] 处中断

-[__NSOrderedSetI objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x8b1fac0

在NSArray和NSOrderedSet中,都有一个文本NS_AVAILABLE(10_8, 6_0);

然而它并没有在 NSArray 上中断,而是在 NSOrderedSet 上中断。为什么?

奖励:我如何使它也适用于 NSOrderedSet 和类别(需要检查它是否尚未定义)

最佳答案

我有更好的答案!

此代码将为不支持 -objectAtIndexedSubscript: 的 iOS 版本动态修补 NSOrderedSet

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

id PatchedObjectAtIndexedSubscript(id self_, SEL cmd_, NSUInteger index)
{
return [self_ objectAtIndex:index];
}

void PatchedSetObjectAtIndexedSubscript(id self_, SEL cmd_, id object, NSUInteger index)
{
return [self_ replaceObjectAtIndex:index withObject:object];
}

void SIPatchNSOrderedSet()
{
char types[6];

if (!class_getInstanceMethod([NSOrderedSet class], @selector(objectAtIndexedSubscript:))) {
sprintf(types, "@@:%s", @encode(NSUInteger));
class_addMethod([NSOrderedSet class],
@selector(objectAtIndexedSubscript:),
(IMP)PatchedObjectAtIndexedSubscript,
types);
}

if (!class_getInstanceMethod([NSMutableOrderedSet class], @selector(setObject:atIndexedSubscript:))) {
sprintf(types, "v@:@%s", @encode(NSUInteger));
class_addMethod([NSMutableOrderedSet class],
@selector(setObject:atIndexedSubscript:),
(IMP)PatchedSetObjectAtIndexedSubscript,
types);
}
}

在您的应用程序开始时(-application:didFinishLaunchingWithOptions: 可能)调用 SIPatchNSOrderedSet()

关于objective-c - someArray[5] 为什么以及如何在 objective-c 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13391251/

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