I had a few questions regarding my objective-C code I wrote and was hoping someone can help clear my doubts. This is my code so far:
This is my Header File:
#import <Foundation/Foundation.h>
@interface Animal : NSObject
@property NSString *name;
@property NSString *favoriteFood;
@property NSString *sound;
@property float weight;
-(instancetype) initWithName:(NSString *) defaultName;
-(void) getInfo;
-(float) getWeightInKg: (float) weightInLbs;
-(NSString *) talkToMe: (NSString *) myName;
-(int) getSum: (int) num1
nextNumber: (int) num2;
@end
This is my Implementation File:
@implementation Animal
- (instancetype)init
{
self = [super init];
if (self) {
self.name = @"No Name";
}
return self;
}
-(instancetype) initWithName:(NSString *) defaultName{
self = [super init];
if (self) {
self.name = defaultName;
}
return self;
}
-(void) getInfo{
NSLog(@"Random Info About Animal");
}
-(float) getWeightInKg:(float)weightInLbs{
return weightInLbs * 0.4545;
}
-(NSString *) talkToMe:(NSString *)myName{
NSString *response = [NSString stringWithFormat: @"Hello my name is %@", myName];
return response;
}
-(int) getSum: (int) num1 nextNumber: (int)num2{
return num1 + num2;
}
@end
This is my main.m file:
#import <Foundation/Foundation.h>
#import "Animal.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Animal *dog = [[Animal alloc]init];
[dog setName:@"Bro"];
NSLog(@"The Dog's name is %@", [dog name]);
Animal *newDog = [[Animal alloc]initWithName:@"Spot"];
NSLog(@"The Dog's weight is equal to %.2f", [newDog getWeightInKg:50]);
NSLog(@"5 + 3 = %d", [newDog getSum:5 nextNumber:3]);
NSLog(@"%@", [newDog talkToMe:@"Bob"]);
}
return 0;
}
I had a few questions regarding this code I wrote:
1) When I define properties such as:
@property NSString *name;
@property NSString *favoriteFood;
@property NSString *sound;
Do I need to synthesize these properties in my implementation file to receive the setter and getter methods? I was a little confused on this since in my main.m file I was able to use the setter method ( [dog setName:@"Bob"] ) for the property: "@property NSString *name;" even though I didn't synthesize that property in my implementation file.
2) Also let's say that I synthesized my name property by doing:
@synthesize name = _name;
What does the _name represent? I read online that it is convention to synthesize a property like this but what is the point of synthesizing and how do I use the "_name" in my implementation or main.m files?
3) In my implementation file in the "-(instancetype)init" method why do we call self = [super init]? What exactly does this "super init" line return in the brackets?
4) Also in my implementation file when I write self.name = @"No Name", what does this self keyword refer to? I read online that "self refers to the actual object that is executing the current method." But my question is what object is this self keyword referring to in my code when I do self.name = @"No Name"?