iphone - 如何编写正确的只读属性?

标签 iphone objective-c properties

我有 2 个关于如何在 Objective-C 2.0+ 中创建正确的只读属性的问题。

这是我原来的方法,我们称之为解决方案 1:

@interface ClassA{
 @private
  NSMutableArray *a_;
}

// NOTE: no retain
@property (nonatomic, readonly) NSMutableArray *a;

@end


///////////////////////////////////////
@implementation ClassA

@synthesize a = a_;

- (NSMutableArray *)a{
  if(nil == a_){
    a_ = [[NSMutableArray alloc] array];
  }
  // Potential leak warning on the following line.
  return a_;
}

- (void)dealloc{
  // I released the object here, I think this should be safe.
  [a_ release];
  [super dealloc];
@end

当我编译分析的时候,系统报了这样一个警告:“a potential leak at 'return a_'”。

然后我又看了一遍Objective-C的文档,找到了另一种方法如下。我们称之为解决方案 2

@interface ClassB{
 @private
  NSMutableArray *a_;
}

// NOTE: make it retain+readonly
@property (nonatomic, readonly, retain) NSMutableArray *a;

@end


///////////////////////////////////////
// Add a private category
@interface ClassB ()

// reset the property to readwrite
@property (nonatomic, readwrite, retain) NSMutableArray *a;

@end

//////
@implementation ClassB

@synthesize a = a_;

- (id)init{
  if(self = [super init]){
    // NOTE: set the value as we use property normally.
    self.a = [NSMutableArray array];
  }
  return self;
}

- (void)dealloc{
  self.a = nil;
  [super dealloc];
@end

现在,这是我的问题:

  • 是否可以使用解决方案 1 并消除“潜在泄漏”?
  • 解决方案 2 是常见解决方案吗?

谢谢大家!

-- 托尼

最佳答案

根据要求,我将我的评论转载为答案:

[[NSMutableArray alloc] array] 应该给你一个编译器警告,它肯定会崩溃。你需要 [[NSMutableArray alloc] init]

关于iphone - 如何编写正确的只读属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4930031/

相关文章:

java - Spring Boot 在从 application.yml 注入(inject) Map 时不包含特殊字符

java - 如何找到生成 DocumentEvent 的源组件

ios - 如何在tableview cell swift 3.0中设置选中的复选标记

iOS 应用程序不会填满 iPhone 屏幕

ios - 使用应用程序上下文从 iPhone 向 WatchOS 发送数据时遇到问题

objective-c - 将大纲 View 的数据源委托(delegate)给单独的对象

ios - 带有管理区域的应用程序可以添加文章

iphone - 崩溃在 actionForLayer :forKey:

objective-c - ios 不兼容的指针类型从 NSError _autoreleasing 分配给 NSError _strong

javascript - D3 圆对象没有属性