I have just started learning Objective-C, and I started by making a basic program that creates a person and prints out its name. However, it doesn't work. What rookie error do you think I have made?
main.m:
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[])
{
Person *Bob;
[Bob setFirstName:@"John"];
[Bob setLastName:@"Smith"];
NSLog(@"%@", [Bob fullName]);
}
Person.h:
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString *firstName;
NSString *lastName;
}
- (void) setFirstName: (NSString*)input;
- (void) setLastName: (NSString*)input;
- (NSString*) firstName;
- (NSString*) lastName;
- (NSString*) fullName;
@end
Person.m:
#import "Person.h"
@implementation Person
// Getters
- (NSString*) firstName
{
return firstName;
}
- (NSString*) lastName
{
return lastName;
}
- (NSString*) fullName
{
return [NSString stringWithFormat:@"%@ %@", firstName, lastName];
}
// Setters
- (void) setFirstName:(NSString *)input
{
firstName = input;
}
- (void) setLastName:(NSString *)input
{
lastName = input;
}
@end
NOTE: This question was originally asked on Code Review StackExchange, but they closed it :-(
The reason it is not working is because you never allocated your Person object correctly.
Notice you never said Bob = [[Person alloc]init];. Objective-C message passing does nothing to null pointers, so that is why you did not get something such as NullPointer. It just silently gets ignored.
For a @property such as firstName and lastName you do not need to create the setters and getters, this is done automatically. For custom setters and getters you will need to create them such as for the fullName property. You also need to allocate and initialize your Person class. The following example should work:
main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *bob = [[Person alloc] init];
bob.firstName = @"Bob";
bob.lastName = @"Williams";
NSLog(@"Full name is %@",bob.fullName);
}
return 0;
}
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (copy,nonatomic) NSString *firstName;
@property (copy, nonatomic) NSString *lastName;
@property (copy, nonatomic) NSString *fullName;
@end
Person.m
#import "Person.h"
@implementation Person
- (NSString *)fullName {
return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With