I got started with Objective C, but i'm not able to understand the basic assingment itself. Below is my code
@interface
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString *_str;
}
-(void) print;
-(id) init;
@end
@implementation
#import "Person.h"
@implementation Person
-(id) init{
self=[super init];
char c[50];
scanf("%s",c);
NSString *xyz=[NSString stringWithUTF8String:c];
NSLog(@"%p",xyz);
_str=xyz;
xyz=@"omg";
NSLog(@"%p",_str);
return self;
}
-(void) print{
NSLog(@"%p",_str);
NSLog(@"%@",_str);
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#import <stdio.h>
int main(int argc, const char * argv[]) {
Person *ob=[[Person alloc] init];
[ob print];
return 0;
}
Code is very simple:
- Get input from console and assign it to local variable
xyz - Assign
xyzto instance varaible_str - Change the value of local variable
xyz
As both xyz and _str are basically pointers, i thought changing value of xyz will change the value of _str too. But I don't see that even-though both variables are pointing to the same location!.Could someone please explain how the assignment is actually working and why updating xyz is not affecting _str.
Output:
My_console_input
2018-05-06 22:28:54.714327+0530 learn_objc1[8109:135801] 0x10051ceb0
2018-05-06 22:28:54.714833+0530 learn_objc1[8109:135801] 0x10051ceb0
2018-05-06 22:28:54.714878+0530 learn_objc1[8109:135801] 0x10051ceb0
2018-05-06 22:28:54.715014+0530 learn_objc1[8109:135801] My_console_input
Program ended with exit code: 0