0

I am having a class as this

@interface SampleClas : NSObject

@property (nonatomic, retain) NSString *var1;
@property (nonatomic, retain) NSArray *var2;
@property (nonatomic, retain ) NSDictionary *var3;
@property (nonatomic, retain ) NSDate *var4;


@end;

Can I use copy instead of retain? Will this not affect memory management in any way?

RK-
  • 12,099
  • 23
  • 89
  • 155

1 Answers1

2

Indeed, many people think that the most correct way to handle immutable oblejcts is through copy and not retain. Have a look at this discussion on S.O.

About, memory management implications, as far as you don't forget to release those copied objects, you are fine. Of course, if you copy very many objects instead of retaining them, your memory consumption will grow locally (because you will have copies around until you release them).

Community
  • 1
  • 1
sergio
  • 68,819
  • 11
  • 102
  • 123
  • For immutable objects that share a mutable version , is copy a good option? And How copying alone can create memory burden? – RK- Dec 03 '11 at 13:28
  • I think so, copy is a good option, since it protect you from the kind of scenario described in the post I linked. As to the memory burden, if you have 10000 object having a `copy` NSString property, and you assign to them, you will end up having 10000 duplicated strings... they will be there until you release the objects... nothing more, nothing less... – sergio Dec 03 '11 at 13:33
  • if you assign through the property (i.e, self.var1 = ...;) the previous contents will be released, you can stay assured. – sergio Dec 03 '11 at 14:57
  • So really using copy will not cause problems if we use self. Am I correct? – RK- Dec 03 '11 at 15:44