【问题标题】:Memory semantics of a computed array property?计算数组属性的内存语义?
【发布时间】:2012-06-01 06:57:34
【问题描述】:

这是一个允许用户标记事物的应用程序。标签只是字符串。

TagHolder 对象数组包含应用程序中正在使用的所有标签的列表,并带有一个布尔值来判断标签是否被选中,但这是一个实现细节。

外部接口调用两个方法,selectedTags 和 setSelectedTags:,它们返回和接受字符串数组。

我希望这两种方法可以用作声明属性 selectedTags 的访问器。

现在,我的问题是:

为该属性声明的正确内存管理语义是什么?

我想到的代码模式是这样的(代码未经测试,所以请多多包涵):

@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

memorytype 应该是什么?显然不强不弱,但我认为它可以是assign、copy 甚至unsafe_unretained 中的任何一个,但是对于具有对象值的计算属性,哪一个最正确?

我通常使用 ARC,但我猜这个问题在手动保留计数的环境中是相同的。

【问题讨论】:

    标签: objective-c cocoa memory-management properties


    【解决方案1】:

    memorytype 仅在您 @synthesize 您的属性访问器时才有意义。由于您为 getter 和 setter 提供了自己的实现,因此您在 @property 之后放在括号中的内容将被忽略;我通常将readonly 或readwrite 放在那里,只是为了提醒自己这些属性有哪些可用的访问权限。

    您的代码是正确的,无论是否使用 ARC,它都可以正常工作而不会产生内存问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 2022-08-17
      相关资源
      最近更新 更多