简体   繁体   中英

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

before ARC I used to write variable in header without use of property:

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

then in .m file I used to retain/release:

-(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. I found the quickest (but dirty) solution by moving the ivar to a @property and using the dot notation.

@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.

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. If you compile without ARC, it won't.

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].

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.

If you were having memory management problems under ARC, it sounds like something else has gone wrong. Did you try build and analyze? Are you sure you turned on ARC for all files?

(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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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