Objective-C set 和 get 方法实现

  • 自定义实现 set 和 get 方法

定义一个 Person 类

  • Person.h
#import 

@interface Person : NSObject

//get
-(NSString *)getName;
-(NSUInteger)getAge;

// set
-(void)setName:(NSString *)n;
-(void)setAge:(NSUInteger)a;

-(void)printInfo;

@end
  • Person.m
#import "Person.h"

@implementation Person
{
    NSString *name;
    NSUInteger age;
}

- (NSString *)getName
{
    return name;
}

- (NSUInteger)getAge
{
    return age;
}

-(void)setName:(NSString *)n
{
    name = n;
}

-(void)setAge:(NSUInteger)a
{
    age = a;
}

- (void)printInfo
{
    NSLog(@"我的名字是: %@ , 年龄是: %lu",name,(unsigned long)age);
}

@end
  • 相关实现
Person *roy = [[Person alloc] init];
[roy setName:@"Roy"];
[roy setAge:18];
        
NSString *name = [roy getName];
NSLog(@" name: %@",name);
        
NSUInteger age = [roy getAge]; // name: Roy
NSLog(@" age: %lu",(unsigned long)age); // age: 18
        
[roy printInfo]; // 我的名字是: Roy , 年龄是: 18

你可能感兴趣的:(Objective-C set 和 get 方法实现)