Did the Target-Action design pattern became bad practice under ARC?

前端 未结 4 514
后悔当初
后悔当初 2021-01-30 11:17

For years I\'ve been following a great pattern called Target-Action which goes like this:

An object calls a specified selector on a specified target object when the time

4条回答
  •  一个人的身影
    2021-01-30 11:23

    The problem with performSelector is that ARC doesn't know what the selector which will performed, does. Consider the following:

    id anotherObject1 = [someObject performSelector:@selector(copy)];
    id anotherObject2 = [someObject performSelector:@selector(giveMeAnotherNonRetainedObject)];
    

    Now, how can ARC know that the first returns an object with a retain count of 1 but the second returns an object which is autoreleased? (I'm just defining a method called giveMeAnotherNonRetainedObject here which returns something autoreleased). If it didn't add in any releases then anotherObject1 would leak here.

    Obviously in my example the selectors to be performed are actually known, but imagine that they were chosen at run time. ARC really could not do its job of putting in the right number of retains or releases here because it simply doesn't know what the selector is going to do. You're right that ARC is not bending any rules and it's just adding in the correct memory management calls for you, but that's precisely the thing it can't do here.

    You're right that the fact you're ignoring the return value means that it's going to be OK, but in general ARC is just being picky and warning. But I guess that's why it's a warning and not an error.

    Edit:

    If you're really sure your code is ok, you could just hide the warning like so:

    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [specifiedReceiver performSelector:specifiedSelector];
    #pragma clang diagnostic pop
    

提交回复
热议问题