gpt4 book ai didi

ios - 在理解部分块时遇到问题

转载 作者:行者123 更新时间:2023-11-29 11:06:45 24 4
gpt4 key购买 nike

我正在努力研究 block 编程,目前陷入了这个问题

char *myCharacters[3] = { "TomJohn", "George", "Charles Condomine" };
qsort_b(myCharacters, 3, sizeof(char *), ^(const void *l, const void *r) {
char *left = *(char **)l;
char *right = *(char **)r;
return strncmp(left, right, 1);
});

第二行是 block 参数 ^(const void *l, const void *r),它从那里获取参数值。

来自苹果Block Programming Topics文档:

Blocks with Cocoa

Several methods in the Cocoa frameworks take a block as an argument, typically either to perform an operation on a collection of objects, or to use as a callback after an operation has finished. The following example shows how to use a block with the NSArray method sortedArrayUsingComparator:. The method takes a single argument—the block. For illustration, in this case the block is defined as an NSComparator local variable:

“在这种情况下, block 被定义为 NSComparator 局部变量”是什么意思?

这是提供的代码示例

NSArray *stringsArray = @[ @"string 1",
@"String 21",
@"string 12",
@"String 11",
@"String 02" ];
static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch |
NSNumericSearch |
NSWidthInsensitiveSearch |
NSForcedOrderingSearch;
NSLocale *currentLocale = [NSLocale currentLocale];
NSComparator finderSortBlock = ^(id string1, id string2) {
NSRange string1Range = NSMakeRange(0, [string1 length]);
return [string1 compare:string2
options:comparisonOptions
range:string1Range
locale:currentLocale];
};
NSArray *finderSortArray = [stringsArray sortedArrayUsingComparator:finderSortBlock];
NSLog(@"finderSortArray: %@", finderSortArray);

^(id string1, id string2) 在哪里获取它的参数值?

最佳答案

NSComparator 实际上是一个类型转换的 block ,typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);typedef double NSTimeInterval; 相同typedef long NSInteger;。由于它是一个 block ,因此格式与参数略有不同。基本上 NSComparator 是一个 block ,它接受两个参数 obj1obj2 并返回一个 NSComparisonResult 值来表示顺序这两个对象。它可以返回 NSOrderedAscendingNSOrderedSameNSOrderedDescendingsortedArrayUsingComparator 可以使用它来重复比较数组中的两个对象并据此对其进行排序。这也有助于实现我们自己的排序实现。当排序发生时,此 block 由 sortedArrayUsingComparator 调用并为 obj1obj2 赋值并执行 NSComparator block .它根据我们实现的比较从该 block 返回 NSComparisonResult

关于ios - 在理解部分块时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13265456/

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