Memory semantics of a computed array property?

久未见 提交于 2019-12-23 10:07:41

问题


This is for an app that allows users to tag things. Tags are just strings.

An array of TagHolder objects holds a list of all tags in use in the app, with a boolean telling if the tag is selected, but this is an implementation detail.

The external interface calls for two methods, selectedTags, and setSelectedTags: which return and accept an arrays of strings.

I would like these two methods to work as accessors for a declared property selectedTags.

Now, my question is:

What would be the correct memory management semantics to declare for that property?

The code pattern that I have in mind is this (code not tested, so please bear with typos):

@interface TagInfo : NSObject
@property (strong, nonatomic) NSString *tag;
@property (nonatomic) BOOL selected;
@end


@interface SomeClass : NSObject
@property (memorytype, nonatomic) NSArray *selectedTags;
@end

@implementation TagHolder

- (NSArray *)selectedTags
{
    // tagInfoArray is an array of all TagInfo objects
    NSPredicate *selPred = [NSPredicate predicateWithFormat: @"selected == YES"];
    NSArray *selectedTagInfoObjects = [[self tagInfoArray] filteredArrayUsingPredicate: selPred];

    NSArray *selectedTags = [selectedTagInfoObjects valueForKey: @"tag"];
    return selectedTags;
}

- (void)setSelectedTags: (NSArray *)selectedTags
{
    for (TagInfo *tagInfo in [self tagInfoArray]) {
        tagInfo.selected = [selectedTags containsObject: tagInfo.tag];
    }
}

@end

What should memorytype be? Obviously not strong or weak, but I think it could be any one of assign, copy or even unsafe_unretained, but which one is the most correct for a computed property with an object value?

I normally use ARC, but I guess the question is the same in an environment with manual retain count.


回答1:


memorytype is significant only when you @synthesize your property accessors. Since you are providing your own implementation for both the getter and the setter, the things you put in parentheses after @property are ignored; I usually put readonly or readwrite there, just to remind myself of what kind of access is available on these properties.

Your code is correct, it will work without creating memory issues with or without ARC.



来源:https://stackoverflow.com/questions/10758715/memory-semantics-of-a-computed-array-property

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