小编smi*_*tty的帖子

使用"copy"属性属性来维护不可变的NSString

我是Objective-C中iOS开发和编程的新手.我一直在app dev库上做练习.

这是我想要了解的当前练习.3.测试如果将可变字符串设置为该人的名字会发生什么,然后在调用修改后的sayHello方法之前改变该字符串.通过添加copy属性更改NSString属性声明并再次测试.

我尝试这样做,但是我修改的NSString实际上改变了,尽管使用了copy属性.

这是我的声明和实现以及我的测试代码.

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" …
Run Code Online (Sandbox Code Playgroud)

attributes copy properties ios

6
推荐指数
1
解决办法
2077
查看次数

标签 统计

attributes ×1

copy ×1

ios ×1

properties ×1