问题
I'm developing an iOs 4 app with latest SDK and XCode 4.2
I have a question about NSString parameters. This is my class definition:
#import <Foundation/Foundation.h>
@interface BlogEntry : NSObject
{
NSString* title;
NSString* text;
NSDate* date;
NSString* photo;
}
- (id)initWithTitle:(NSString*)titulo text:(NSString*)texto date:(NSDate*)fecha photo:(NSString*)foto;
@end
And implementation:
#import "BlogEntry.h"
@implementation BlogEntry
- (id)initWithTitle:(NSString*)titulo text:(NSString*)texto date:(NSDate*)fecha photo:(NSString*)foto
{
if (self = [super init])
{
title = titulo;
text = texto;
date = fecha;
photo = foto;
}
return self;
}
@end
May I need to retain initWithTitle parameters? Or, may I have to copy them?
回答1:
If ARC, no. If non-ARC, yes.
For the NSString ivars, usually copy. For the NSDate ivar, retain. The reason for copy with NSString is in case an NSMutableString is passed in your init method. Copying the parameter prevents it from being mutated by your class. Thus, it ensures encapsulation.
来源:https://stackoverflow.com/questions/9700755/copy-or-retain-nsstring-parameter