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

前端 未结 4 508
后悔当初
后悔当初 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:22

    The warning should read like this:

    PerformSelector may cause a leak because its selector is unknown. ARC doesn't know if the returned id has a +1 retain count or not, and therefore can't properly manage the memory of the returned object.

    Unfortunately, it's just the first sentence.

    Now the solution:

    If you receive a return value from a -performSelector method, you can't do anything about the warning in code, except ignoring it.

    NSArray *linkedNodes = [startNode performSelector:nodesArrayAccessor];
    

    Your best bet is this:

    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    NSArray *linkedNodes = [startNode performSelector:nodesArrayAccessor];
    #pragma clang diagnostic pop
    

    Same goes for the case in my initial question, where I completely ignore the return value. ARC should be intelligent enough to see that I don't care about the returned id, and therefore the anonymous selector is almost guaranteed not to be a factory, convenience constructor or whatsoever. Unfortunately ARC is not, so the same rule applies. Ignore the warning.

    It can also be done for the whole project by setting the -Wno-arc-performSelector-leaks compiler flag under "Other Warning Flags" in project build settings.

    Alternatively, you can surpress the warning on a per-file basis when you add that flag under Your Target > "Build Phases" > "Compile Sources" on the right-hand side next to the desired file.

    All three solutions are very messy IMHO so I hope someone comes up with a better one.

提交回复
热议问题