简体   繁体   English

用于重写Objective-C ARC中@property的代码

[英]Code rewriting for getting rid of @property in objective-c ARC

before ARC I used to write variable in header without use of property: 在ARC之前,我曾经在不使用属性的情况下在标头中写入变量:

@interface MyViewController : UIViewController {
  NSString *prop1;
}
@end

then in .m file I used to retain/release: 然后在.m文件中,我用来保留/释放文件:

-(void)initVar {
  prop = @"initialized variable";
  [prop retain];
}

-(void)dealloc{
  [prop release];
}

After having tried ARC for a while, I get lot of memory management problem, in a sense that many object were deallocated. 在尝试了一段时间的ARC之后,从某种意义上说,许多对象都被释放了,我遇到了很多内存管理问题。 I found the quickest (but dirty) solution by moving the ivar to a @property and using the dot notation. 通过将ivar移至@property并使用点表示法,我找到了最快(但较脏)的解决方案。

@interface MyViewController : UIViewController

@property(strong) NSString *prop;

@end  

I later added a readonly attribute for there were no need to access outside the controller. 后来我添加了一个只读属性,因为不需要在控制器外部访问。 My question is, in ARC environment how can I rewrite the above code to ged rid of @property, in particular my concern is about view controllers, they can get alloc/dealloc many times during the life of the application. 我的问题是,在ARC环境中,我该如何重写以上代码以摆脱@property的困扰,尤其是我对视图控制器的关注,它们在应用程序的生存期内可以多次分配/取消分配。

Honestly, your question and your pseudo-code don't make much sense. 老实说,您的问题和伪代码没有多大意义。 Under ARC, an ivar will be a strong reference to an object [by default] and, thus, assignments to/from that ivar will be managed like all other ARC-ified objects. 在ARC中,[默认情况下] ivar是对象的强引用,因此,与所有其他ARC标准化的对象一样,对ivar的分配/来自该ivar的分配也将得到管理。 If you compile without ARC, it won't. 如果在没有ARC的情况下进行编译,则不会。

The issue of whether you use ivars or properties for your code is a style question and has little to do with memory management [under ARC -- under MRR you would need to manually manage the ivar references]. 是否为代码使用ivars或属性是一个样式问题,与内存管理无关(在ARC中-在MRR下,您需要手动管理ivar引用)。

Both your initializer example and your -dealloc are wrong, in your question, but that may just be because they were quick notes and not real code. 在您的问题中,初始化程序示例和-dealloc都是错误的,但这可能只是因为它们只是快速注释,而不是真正的代码。

If you were having memory management problems under ARC, it sounds like something else has gone wrong. 如果您在ARC下遇到内存管理问题,听起来好像其他地方出了问题。 Did you try build and analyze? 您是否尝试构建和分析? Are you sure you turned on ARC for all files? 您确定已打开所有文件的ARC吗?

(Note, I've been using ARC for quite a while and it is, generally, a "just works" experience. I have yet to run into any serious issues save for a couple of compiler bugs and the brittle border between NS and CF code). (请注意,我使用ARC已经有一段时间了,通常来说,这是一种“正常工作”的经验。除了几个编译器错误以及NS和CF之间的脆弱边界之外,我还没有遇到任何严重的问题。码)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM