【问题标题】:ObjC/ARC ByRef in For loopFor 循环中的 ObjC/ARC ByRef
【发布时间】:2013-01-16 17:52:36
【问题描述】:

我有一个 for 循环,然后将迭代对象传递给一个带有 byref 参数的方法并得到以下错误:

Implicit conversion of an Objective-C pointer to 'FOO *__autoreleasing *' is disallowed with ARC

和警告:

Incompatible pointer types sending 'Foo *const __strong' to parameter of type 'Foo *__autoreleasing *'

循环:

for (Foo *obj in objArray) {
    FooTableCell *newCell = [self createFooCellWithItem:obj];
}

方法签名:

-(FooTableCell *)createFooCellWithItem:(Foo **)newObj;

我已按照this SO q&a 的建议无济于事。

编辑

在 obj 之前添加 & 会给我以下错误:

Sending 'Foo *const __strong *' to parameter of type 'Foo *__autoreleasing *' changes retain/release properties of pointer

【问题讨论】:

    标签: ios objective-c ios6 automatic-ref-counting pass-by-reference


    【解决方案1】:

    作为聊天中讨论和发现的简历,这里有几个注意事项。

    您似乎正在尝试:

    1. 快速迭代数组;而

    2. 替换循环内部调用的方法中的每个数组元素;

    编译器不允许这样做。它至少会打破关于不修改枚举中的数组的快速枚举约定。

    因此,我的建议是在您的 shouldAddObject 方法中明确指定一个输出参数,例如:

    NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:[objArray count]]; 
    for (Foo *obj in objArray) {
        Foo* newObject = nil;
        RETYPE* ret = [self shouldAddObject:obj newObject:&newObject]; 
        [newArray addObject:newObject];
    }
    

    【讨论】:

    • 我试过了,我得到以下错误:将'Foo *const __strong *'发送到'Foo *__autoreleasing *'类型的参数更改指针的保留/释放属性
    • 现在 ARC 只是一种痛苦:使用 __bridge 强制转换将 'Foo *const __strong *' 转换为 'Foo *__strong *' 的不兼容类型
    • 和ObjC如何循环创建迭代器obj有关系吗?
    • 一个问题:你为什么要传递一个Foo**?你是在shouldAddObject里面分配对象吗?
    【解决方案2】:

    如果我记得数组都是指针的集合,那么您可能已经这样做了,在这种情况下,您只需更改您的 shouldAddObject

     -(void)shouldAddObject:(Foo *)newObj {
          // Do your thing
     }
    

    或使用标志 -fno-objc-arc 关闭该文件的 ARC。

    但是,如果不是这种情况,您可以使用 ARC 执行此操作:

     - (void)swapObjCPointers:(id*)ptrA with:(id*)ptrB {
    
         // Puts pointer B into pointer A
         id this = *ptrB;
         *ptrB = *ptrA;
         *ptrA = this;
    
     }
    

    例子:

    @implementation MyARCFile
    
     - (void)swapObjCPointers:(id*)ptrA with:(id*)ptrB {
    
         // Puts pointer B into pointer A
         id this = *ptrB;
         *ptrB = *ptrA;
         *ptrA = this;
    
     }
    
    
    - (void)example {
    
         id objA = [NSObject new];
         id objB = @"String";
    
         NSLog(@"\n"
               @"a: %p\n"
               @"b: %p\n",
               objA,
               objB);
    
         [self swapObjCPointers:&objA with:&objB];
    
         NSLog(@"\n"
               @"a: %p\n"
               @"b: %p\n",
               objA,
               objB);
     }
    
     @end
    

    有什么帮助吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多