iOS and mutable IBOutletCollections

梦想的初衷 提交于 2019-12-06 09:34:53

问题


I have the property:

@property(nonatomic, strong) IBOutletCollection(UIView) NSMutableArray *allOpposition;

which is wired up in IB to a bunch of subviews and synthesized. Later I have:

- (void)willRemoveSubview:(UIView *)subview
{
  [[self allOpposition] removeObject:subview]; // Crash occurs here.
  [super willRemoveSubview:subview];
}

When the time comes to remove the view representing an opposing entity, I get the following error message:

-[__NSArrayI removeObject:]: unrecognized selector sent to instance 0x88211c0

The object is not nil and is contained in the collection. How come my array is immutable?

Remark: Quite possibly Apple requires each object in the collection to be of type UIView, in this case. If the array were fully mutable conceivably I could add foreign types. I haven't found much documentation here so this is speculation on my part.

Remark: I don't see the value of allowing a mutable array to be passed in if the returned array is ultimately immutable. Why not just accept immutable arrays?


回答1:


You may have declared the property as a mutable array, but I'm pretty sure that when your nib is loaded an immutable array will be assigned to it.

Override the synthesised setter for allOpposition (I'm assuming you're using xcode4.4 or later and ARC):

-(void)setAllOpposition:(NSMutableArray*)allOpposition
{
    _allOpposition = [allOpposition mutableCopy];
}

You may also be able to achieve this by changing the property declaration from strong to copy, but that's a guess.



来源:https://stackoverflow.com/questions/12576780/ios-and-mutable-iboutletcollections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!