使用 'NSString *' 类型的表达式初始化 'dispatch_source_t'(又名 'NSObject<OS_dispatch_source> *')的不兼容指针类型

Incompatible pointer types initializing 'dispatch_source_t' (aka 'NSObject<OS_dispatch_source> *') with an expression of type 'NSString *'

嗨,我是 Objective-c 的学习者,收到 Incompatible pointer types initializing 'dispatch_source_t' (aka 'NSObject<OS_dispatch_source> *') with an expression of type 'NSString *'

的警告
- (void)stopAnimating {
    pause = YES;

    if (timerArray) {
        for (NSInteger i = 0; i < [timerArray count]; i++) {
            dispatch_source_t _timer = [[timerArray objectAtIndex:i] source];
            dispatch_source_cancel(_timer);
            _timer = nil;
        }
    
        timerArray = nil;
    }

    [self removeAllFlakesWithAnimation:YES];
}

dispatch_source_t _timer = [[timerArray objectAtIndex:i] source];这一行,怎么解决,timeArray是一个NSMutableArrayNSMutableArray *timerArray;

我们无法告诉您您的代码有什么问题,因为没有足够的信息,但我们可以告诉您编译器正在做什么以及它为什么会产生错误 – 然后您就会知道从那里解决它。

在你的行中:

dispatch_source_t _timer = [[timerArray objectAtIndex:i] source];

LHS 声明的是 _timer 类型的 dispatch_source_t 变量,因此 RHS 需要 return 这种类型的值。让我们看看RHS:

[timerArray objectAtIndex:i]

顺便说一句,您可以更简洁地写成:

timerArray[i]

此索引到您已声明为的数组中:

NSMutableArray *timerArray;

像这样的数组的元素具有类型 id – 这意味着对 any 对象的引用。在这种情况下,数组中对象的实际类型要到运行时才能知道。 RHS的下一部分是:

[<a reference so some object> source]

Objective-C 允许这样做并将在运行时执行检查以确定引用对象确实具有方法 source。然而在编译时,编译器可以查找名为 source 的方法的定义,它确实如此,并发现方法 return 是一个 NSString *.

因此 RHS return 是 NSString * 而 LHS 需要 dispatch_source_t 因此编译器报告:

Incompatible pointer types initializing 'dispatch_source_t' (aka 'NSObject<OS_dispatch_source> *') with an expression of type 'NSString *'

现在你必须弄清楚你是打算调用 source 还是其他一些方法 return 一个正确类型的值,等等。HTH


作为学习者的另一个 BTW Objective-C:您正在使用 for 循环为数组生成索引值,并且您仅使用该值对数组进行一次索引。更好的方法是使用 for/in 循环:

for (<YourObjectType> element in timerArray) {
   dispatch_source_cancel([element source]);
}

您需要将 <YourObjectType> 替换为您存储在 timerArray 中的对象引用类型,并且如上所述 source 方法需要 return dispatch_source_t值。

Objective-C 有一个 for ... 但是还有其他非常好的方法可以迭代数组的元素。我举一个数组 a 的例子,在本例中是 NSString *

    [a enumerateObjectsUsingBlock: ^ ( NSString * i, NSUInteger idx, BOOL * stop ) {

        // do something with NSString * i
        // its index into the array is idx if you need it
        // to exit out of the loop do
        * stop = YES;

    }];