• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Objective C属性关键字

武飞扬头像
Zyryck
帮助1

成员变量访问赋值的两种方式:

一.get set方式

  1.  
    @interface Person : NSObject{
  2.  
    //成员变量
  3.  
    NSString* _name;
  4.  
    }
  5.  
    -(void)setName:(NSString*)name;
  6.  
    -(NSString*)name;
  7.  
    @end
  1.  
    #import <Foundation/Foundation.h>
  2.  
    #import "Person.h"
  3.  
     
  4.  
     
  5.  
    int main(int argc, const char * argv[]) {
  6.  
    @autoreleasepool {
  7.  
    Person* p1 = [Person new];
  8.  
    [p1 name];
  9.  
    [p1 setName:@"dancer"];
  10.  
     
  11.  
    }
  12.  
    return 0;
  13.  
    }

二.属性方式

1.@property(strong, nonatomic)

  1.  
    @interface Person : NSObject{
  2.  
    //成员变量
  3.  
    NSString* _name;
  4.  
    }
  5.  
    //属性
  6.  
    @property(strong, nonatomic)NSString* name;
  7.  
    @end
  1.  
    #import <Foundation/Foundation.h>
  2.  
    #import "Person.h"
  3.  
     
  4.  
     
  5.  
    int main(int argc, const char * argv[]) {
  6.  
    @autoreleasepool {
  7.  
    Person* p1 = [Person new];
  8.  
    p1.name = @"dancer";
  9.  
    NSString* name = p1.name;
  10.  
    NSLog(@"name = %@",name);
  11.  
    }
  12.  
    return 0;
  13.  
    }

2.声明property声明synthesize

  1.  
    #import <Foundation/Foundation.h>
  2.  
     
  3.  
    NS_ASSUME_NONNULL_BEGIN
  4.  
     
  5.  
    @interface Person : NSObject{
  6.  
    NSInteger _age;
  7.  
    }
  8.  
    //属性
  9.  
    @property(assign, nonatomic)NSInteger age;
  10.  
    @end
  11.  
     
  12.  
    NS_ASSUME_NONNULL_END
  1.  
    #import "Person.h"
  2.  
     
  3.  
    @implementation Person
  4.  
     
  5.  
    @synthesize age;
  6.  
     
  7.  
    @end

3.省略成员变量的属性方式

  1.  
    #import <Foundation/Foundation.h>
  2.  
     
  3.  
    NS_ASSUME_NONNULL_BEGIN
  4.  
     
  5.  
    @interface Person : NSObject{
  6.  
    NSInteger _age;
  7.  
    }
  8.  
    //属性
  9.  
    @property(strong, nonatomic)NSString* name;
  10.  
    @property(assign, nonatomic)NSInteger age;
  11.  
    //没有对应的成员变量可以自动生成一个私有的成员变量 _属性名
  12.  
    @property(assign, nonatomic)NSInteger weight;
  13.  
    @end
  14.  
     
  15.  
    NS_ASSUME_NONNULL_END
学新通

使用synthesize修改自动生成的成员变量的名字

  1.  
    #import "Person.h"
  2.  
     
  3.  
    @implementation Person
  4.  
     
  5.  
    @synthesize age;
  6.  
    //使用synthesize修改自动生成的成员变量的名字
  7.  
    @synthesize weight = _myWeight;
  8.  
    @end

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhibjbcj
系列文章
更多 icon
同类精品
更多 icon
继续加载