I have 2 questions.
First - Are string declared as such in obj-c
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *city;
Are those (nonatomic, copy)
right or should I use (nonatomic, strong)
, or something else ?
Second - If I want to set custom initializer for above strings do I use
-(id)initWithName:(NSString *)n andCity:(NSString *)c
{
self = [super init];
if (self) {
self.name = n;
self.city = c;
}
}
or should I use:
-(id)initWithName:(NSString *)n andCity:(NSString *)c
{
self = [super init];
if (self) {
self.name = [n copy]
self.city = [c copy];
}
}
As I can see both ways seem to work for both questions but I'm sure one is more correct than the other, so I wanted to ask which should I use to write correct code in further projects.
Thanks.
First - it doesn't really matter if you use copy
or strong
. Personally i prefer to copy strings rather than retain them
Second - `
-(id)initWithName:(NSString *)n andCity:(NSString *)c
{
self = [super init];
if (self) {
self.name = n;
self.city = c;
}
}`
You don't need to use copy
message once more cause your properties will copy n and c. If you apply your second piece of code you'll copy n and c twice and have a memory leak