zoukankan      html  css  js  c++  java
  • Objective-C基础5 : 属性@property

    1.类里面经常有一些变量需要进行set和get操作,OC中提供了方便的属性@property来替换set和get方法,这样能减少频繁且简单的重复代码。如下代码:

    @interface Person : NSObject
    @property NSString* strName;
    @property int nAge;
    @end
    @implementation Person @synthesize strName; @synthesize nAge; @end

    通过在类声明变量前面添加@property表明这个变量是个属性变量@property NSString* strName,在类实现里面添加@synthesize让XCode为你生成编译代码@synthesize strName。实际上xcode编译器会在编译的时候自动为这个属性添加set和get方法,如上面例子中的StrName在类里面添加了方法setStrName和strName,我们可以通过方法设置和访问strName。但是方便的方法是通过.来访问。

     @autoreleasepool {
            // insert code here...
            Person* p = [[Person alloc] init];
            p.strName = @"52xpz";
            p.nAge = 16;
            NSLog(@"name:%@, age:%d", p.strName, p.nAge);
            NSLog(@"name:%@, age:%d", [p strName], [p nAge]);
            [p setStrName:@"akon"];
            [p setNAge:18];
            NSLog(@"name:%@, age:%d", p.strName, p.nAge);
            NSLog(@"name:%@, age:%d", [p strName], [p nAge]);
            
        }

    2.@property有一些可选项,比如copy(复制),retain(保留)、readonly(只读)、readwrite(可读写)、nonatomic(不要原子话访问)、assign(简单地赋值)。

    属性默认是assgin和atomic选项。下面代码声明了strName为copy, readwrite;eye为retain, readwrite, nonatomic。方便啊!

    @interface Person : NSObject
    
    @property (copy, readwrite) NSString* strName;
    @property int nAge;
    @property (retain, readwrite, nonatomic) Eye* eye;
    @end

     如何不让编译器为我们生成属性代码而是用自己的代码呢?答案@dynamic关键字。

    @interface Person : NSObject
    
    @property (readonly) int nAge;
    
    @end
    
    @implementation Person
    
    @dynamic nAge;
    
    -(int) nAge
    {
        return  10;
    }
    
    @end
    

     3.关于属性的选择个人认为有一下几个原则:

        1)set和get只要一个参数设置变量用属性,有两个及以上参数设置变量不应该用。

        2)代码都是简单地设置和获取变量应该用属性,减少代码量的同时代码简单、可读性好。

    参考资料: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html

  • 相关阅读:
    传智博客.NET培训第13季 Ajax教程(共十三季) 学习资源
    一些sql语句的常用总结(重要)
    处理oracle的死锁
    Adroid 总结--android ListView美化,个性化更改的属性
    如何远程备份sql server数据库
    VSS (Visual Source Safe 2005) 用法详解
    php插入代码数据库
    PHP之PHP文件引用详解
    需要引入库:vue-resource
    axios调用详解
  • 原文地址:https://www.cnblogs.com/52xpz/p/4266211.html
Copyright © 2011-2022 走看看