Skip to content

Instantly share code, notes, and snippets.

@oney
Last active February 20, 2016 08:11
Show Gist options
  • Save oney/ffc03572525afb2916c6 to your computer and use it in GitHub Desktop.
Save oney/ffc03572525afb2916c6 to your computer and use it in GitHub Desktop.
Copy property on Objective-C

Testing Copy property on Objective-C

#import "AppDelegate.h"
#import "Model.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
Model *model = [Model new];
[model go];
return YES;
}
#import <Foundation/Foundation.h>
#import "Sub.h"
@interface Model : NSObject
@property (nonatomic, readwrite, copy) Sub *sub;
@property (nonatomic, readwrite, copy) NSString *str;
@property (nonatomic, readwrite, copy) NSMutableString *mutableStr;
- (void)go;
@end
#import "Model.h"
@implementation Model
- (instancetype)init {
self = [super init];
if (self) {
_sub = [Sub new];
_str = @"hello";
_mutableStr = [[NSMutableString alloc] initWithString:@"hello"];
}
return self;
}
- (void)go {
Sub *sub = [Sub new];
NSLog(@"sub1: %p", self.sub); // sub1: 0x7fda30527250
NSLog(@"sub2: %p", sub); // sub2: 0x7fda30527290
self.sub = sub;
NSLog(@"sub3: %p", self.sub); // sub3: 0x7fda30615e00
self.sub = self.sub;
NSLog(@"sub4: %p", self.sub); // sub4: 0x7fda307a0010
NSString *str = @"world";
NSLog(@"str1: %p", self.str); // str1: 0x1083fe080
NSLog(@"str2: %p", str); // str2: 0x1083fe120
self.str = str;
NSLog(@"str3: %p", self.str); // str3: 0x1083fe120
self.str = self.str;
NSLog(@"str4: %p", self.str); // str4: 0x1083fe120
NSMutableString *mutableStr = [[NSMutableString alloc] initWithString:@"hello"];
NSLog(@"mutableStr1: %p", self.mutableStr); // mutableStr1: 0x7fbb430085c0
NSLog(@"mutableStr2: %p", mutableStr); // mutableStr2: 0x7fbb41520350
self.mutableStr = mutableStr;
NSLog(@"mutableStr3: %p", self.mutableStr); // mutableStr3: 0xa00006f6c6c65685
self.mutableStr = self.mutableStr;
NSLog(@"mutableStr4: %p", self.mutableStr); // mutableStr4: 0xa00006f6c6c65685
self.mutableStr = mutableStr;
NSLog(@"mutableStr5: %p", mutableStr); // mutableStr5: 0x7fbb41520350
NSLog(@"mutableStr6: %p", self.mutableStr); // mutableStr6: 0xa00006f6c6c65685
[mutableStr appendString:@" world"];
NSLog(@"mutableStr7: %@", self.mutableStr); // mutableStr7: hello
NSLog(@"mutableStr8: %@", mutableStr); // mutableStr8: hello world
self.mutableStr = mutableStr;
NSLog(@"mutableStr9: %p", self.mutableStr); // mutableStr9: 0x7fbb417a2f90
}
@end
#import <Foundation/Foundation.h>
@interface Sub : NSObject <NSCopying>
@end
#import "Sub.h"
@implementation Sub
- (instancetype)copyWithZone:(NSZone *)zone {
Sub *copy = [[[self class] allocWithZone:zone] init];
return copy;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment