【问题标题】:Incompatible pointer types initializing 'dispatch_source_t' (aka 'NSObject<OS_dispatch_source> *') with an expression of type 'NSString *'使用“NSString *”类型的表达式初始化“dispatch_source_t”(又名“NSObject<OS_dispatch_source> *”)的不兼容指针类型
【发布时间】:2020-11-17 03:44:15
【问题描述】:

您好,我是 Objective-c 的学习者,收到 Incompatible pointer types initializing 'dispatch_source_t' (aka 'NSObject&lt;OS_dispatch_source&gt; *') 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;

【问题讨论】:

    标签: ios objective-c uiview


    【解决方案1】:

    我们无法告诉您代码有什么问题,也没有足够的信息来说明这一点,但我们可以告诉您编译器在做什么以及为什么会产生错误 - 然后您必须解决从那里开始。

    在你的行中:

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

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

    [timerArray objectAtIndex:i]
    

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

    timerArray[i]
    

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

    NSMutableArray *timerArray;
    

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

    [<a reference so some object> source]
    

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

    所以 RHS 返回一个 NSString *,而 LHS 需要一个 dispatch_source_t,因此编译器报告:

    使用“NSString *”类型的表达式初始化“dispatch_source_t”(又名“NSObject&lt;OS_dispatch_source&gt; *”)的不兼容指针类型

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


    作为另一个学习 Objective-C 的人的顺便说一句:您正在使用 for 循环为数组生成索引值,并且您只使用该值来索引数组一次。更好的方法是使用for/in 循环:

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

    您需要将&lt;YourObjectType&gt; 替换为您存储在timerArray 中的对象引用类型,并且如上所述,source 方法需要返回一个dispatch_source_t 值。

    【讨论】:

    • “像这样的数组的元素具有类型 id——这意味着对任何对象的引用”......我可能会建议使用轻量级泛型而不是 NSMutableArray *timerArray,例如 NSMutableArray &lt;MyObject *&gt; *timerArray,即MyObject 的数组(显然将MyObject 替换为与数组中的内容相对应的名称)。这提供了更好的 Obj-C 编译时检查和更好的 Swift 互操作性。 (我知道你可能知道这一点,但为了未来的读者。)
    【解决方案2】:

    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;
    
        }];
    

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多