NSString (pointer / not pointer) assigns or stores

I have four variants of the same class.

Confusing pointer, not pointer, vs copy assignment.

What are the implications of using each case?

1)

@interface fruit: NSObject {
NSString apple;
}
@property (nonatomic, retain);
@end

2)

@interface fruit: NSObject {
NSString apple;
}
@property (nonatomic, assign);
@end

3)

@interface fruit: NSObject {
NSString * apple;
}
@property (nonatomic, retain);
@end

4)

@interface fruit: NSObject {
NSString * apple;
}
@property (nonatomic, assign);
@end
+2


source to share


2 answers


1)

@interface fruit:NSObject{
NSString apple;
}
@property(nonatomic, retain);
@end

      

You cannot allocate NSObjects

on the stack or object instance variables. Objective-C used to allow this, but it doesn't happen anymore. This code is incorrect.



2)

@interface fruit:NSObject{
NSString apple;
}
@property(nonatomic, assign);
@end

      

You cannot allocate NSObjects

on the stack or object instance variables. Objective-C used to allow this, but it doesn't happen anymore. This code is incorrect.



3)

@interface fruit:NSObject{
NSString *apple;
}
@property(nonatomic, retain);
@end

      

You retain your interest in the copy NSString

, ensuring that it will not be released as long as you retain that ownership. Because it NSMutableString

is a subclass NSString

, you might be assigned a mutable string when assigned, so other code might change the string value without your knowledge (unless you use key-value monitoring to watch for these changes). For this reason, it is advisable to use the usual semantics copy

for properties that you intend to keep unchanged the value of ( NSString

, NSData

, NSArray

, NSSet

are common, though not exaustive - suspects).

4)

@interface fruit:NSObject{
NSString *apple;
}
@property(nonatomic, assign);
@end

      

You do not retain ownership of the string, which means it could be released without your knowledge. In reference counting environments, this is standard practice for delegate properties, since storing them will likely create a persistence loop. The code responsible for freeing the string must set your apple property to nil before doing so (in a counting environment). In a GC environment, your job will keep the string alive if you have a __strong pointer, or you get zeroed out (set to 0 on dealloc) if you have a __weak pointer in your declaration.

+9


source


As far as I know you should always use either save or copy using NSString *. Assigning to pointer (4) does not increment the reference count, so there will be a memory leak, or rather, it means that you will access the released memory as the counter will prematurely reach 0.



I don't know if you can use NSString as a native type. I always use it as a pointer.

+2


source







All Articles