Copy or retain NSString parameter?

烂漫一生 提交于 2020-01-04 02:40:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!