我对 iOS 开发和 Objective-C 编程非常陌生。我一直在应用开发库上做练习。
这是我试图理解的当前练习。3. 测试如果将可变字符串设置为人的名字会发生什么,然后在调用修改后的 sayHello 方法之前改变该字符串。通过添加复制属性来更改 NSString 属性声明并再次测试。
但是,我尝试这样做,尽管使用了复制属性,我修改的 NSString 实际上确实发生了变化。
这是我的声明和实现以及我的测试代码。
XYZPerson.h
#import <Foundation/Foundation.h>
@interface XYZPerson : NSObject
@property (copy) NSString *firstName;
@property NSString *lastName;
@property NSDate *dob;
- (void)sayHello;
- (void)saySomething:(NSString *)greeting;
+ (id)init;
+ (id)personWithFirstName:(NSString *)firstName lastName:(NSString *)lastName dob:(NSDate *)dateOfBirth;
@end
//XYZPerson.m
#import "XYZPerson.h"
@implementation XYZPerson
@synthesize firstName = _firstName;
@synthesize lastName = _lastName;
@synthesize dob = _dob;
- (void)sayHello {
[self saySomething:@"Hello World!"];
NSLog(@"This is %@ %@", self.firstName, self.lastName);
}
- (void)saySomething:(NSString *)greeting {
NSLog(@"%@", greeting);
}
+ (id)init {
return [self personWithFirstName:@"Yorick" lastName:@"Robinson" dob:8/23/1990];
}
+ (id)personWithFirstName:(NSString *)firstName lastName:(NSString *)lastName dob:(NSDate *)dateOfBirth{
XYZPerson *person = [[self alloc] init];
person.firstName = firstName;
person.lastName = lastName;
person.dob = dateOfBirth;
return person;
}
@end
//Test code
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "XYZPerson.h"
#import "XYZShoutingPerson.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
XYZPerson *guy = [XYZPerson init];
[guy sayHello];
//I thought that this change would never be made, but it is everytime I run the code.
guy.firstName = @"Darryl";
[guy sayHello];
XYZShoutingPerson *girl = [XYZShoutingPerson init];
[girl sayHello];
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}