相关疑难解决方法(0)

在init和dealloc方法中有效使用访问器?

我现在从几个来源(stackoverflow.com,cocoa-dev,文档,博客等)中听到,在init和dealloc方法中使用访问器和设置(foo,setFoo :)是"错误的".据我所知,如果你这样做,很可能会混淆其他正在观察财产的物体.(这里给出一个简单的例子)

但是,由于以下原因,我不得不说我不同意这种做法:

新的Objective-C运行时(iPhone上的那个和10.5中的64位运行时)允许您在声明相应的ivar的情况下声明属性.例如,以下类将在10.5或iPhone(设备,而不是模拟器)上编译得很好:

@interface Foo : NSObject { }

  @property (retain) id someObject;

@end

@implementation Foo

  @synthesize someObject;

@end
Run Code Online (Sandbox Code Playgroud)

理解上面是一个完全有效的Objective-C类,假设我决定编写一个初始化程序,并且出于内存管理的目的,使用dealloc方法(因为在iPhone上没有GC).我读过有关初始化器和释放器的所有内容都会让我编写以下两种方法:

- (id) init {
  if (self = [super init]) {
    //initialize the value of someObject to nil
    [self setSomeObject:nil];
  }
  return self;
}

- (void) dealloc {
  //setting someObject to nil will release the previous value
  [self setSomeObject:nil];
  [super dealloc];
}
Run Code Online (Sandbox Code Playgroud)

但是,根据文件和流行的观点,这是"错误的".所以我的问题是这样的:

  1. 如何在不使用访问器的情况下初始化someObject?您可能会说编译器(或运行时或其他)将确保someObject已设置为nil,但我相信依赖它会是不正确的行为.在C语言中有一个不错的背景,由于没有正确初始化变量,我看到了相当数量的错误,这似乎没有什么不同.
  2. 如果我不应该在dealloc方法中使用访问器,我该如何释放someObject?

如果其中任何一个的答案是"你不能",那么在init和dealloc方法中使用访问器怎么可能不好?

initialization properties objective-c accessor dealloc

24
推荐指数
2
解决办法
5180
查看次数

在类中声明一个retain属性,编译器默认会将[property release]添加到-dealloc吗?

可能重复:
是否需要释放Objective-c 2.0属性的内存?

例如:

@interface DataMode : NSObject {
    NSString * name;
}

@property (nonatomic, retain) NSString * name;

@end
Run Code Online (Sandbox Code Playgroud)

将编译器自动添加[name release]-dealloc

- (void) dealloc
{
   [name release];    // if we  don't add it , will the compiler add "[name release]"???
   [super release];     

}
Run Code Online (Sandbox Code Playgroud)

memory-management properties objective-c retain

0
推荐指数
1
解决办法
199
查看次数