Declared property

A declared property provides a syntactical shorthand for declaring a class’s accessor methods and, optionally, implementing them. You can declare a property anywhere in the method declaration list, which is in the interface of a class, or in the declaration of a protocol or category. You use the following syntax:

@property (<#attributes#>) <#type#> <#name#>;

You begin a property declaration with the keyword @property. You can then optionally provide a parenthesized set of property attributes that define the storage semantics and other behaviors of the property. (Refer to the document that definitively describes property lists for descriptions of these attributes.)

Each property declaration ends with a type specification and a name. For example:

@property(copy) NSString *title;

This syntax is equivalent to declaring the following accessor methods:

- (NSString *)title;
- (void)setTitle:(NSString *)newTitle;

In addition to declaring the accessor methods, you can instruct the compiler to synthesize implementations of them (or inform the compiler that your class will synthesize them at runtime).

You use the @synthesize statement in a class’s implementation block to tell the compiler to create implementations that match the specification you gave in the property declaration.

@interface MyClass : NSObject
{
    NSString *title;
}
@property(copy) NSString *title;
@end
 
@implementation MyClass
@synthesize title;
@end

You use the @dynamic statement to tell the compiler to suppress a warning if it can’t find an implementation of accessor methods specified by an @propertydeclaration.

@implementation MyClass
@dynamic title;
@end

Prerequisite Articles

Related Articles

(None)

Most Properties Are Backed by Instance Variables

By default, a readwrite property will be backed by an instance variable, which will again be synthesized automatically by the compiler.

An instance variable is a variable that exists and holds its value for the life of the object. The memory used for instance variables is allocated when the object is first created (through alloc), and freed when the object is deallocated.

Unless you specify otherwise, the synthesized instance variable has the same name as the property, but with an underscore prefix. For a property called firstName, for example, the synthesized instance variable will be called _firstName.

Although it’s best practice for an object to access its own properties using accessor methods or dot syntax, it’s possible to access the instance variable directly from any of the instance methods in a class implementation. The underscore prefix makes it clear that you’re accessing an instance variable rather than, for example, a local variable:

- (void)someMethod {
    NSString *myString = @"An interesting string";
 
    _someString = myString;
}

In this example, it’s clear that myString is a local variable and _someString is an instance variable.

In general, you should use accessor methods or dot syntax for property access even if you’re accessing an object’s properties from within its own implementation, in which case you should use self:

- (void)someMethod {
    NSString *myString = @"An interesting string";
 
    self.someString = myString;
  // or
    [self setSomeString:myString];
}

The exception to this rule is when writing initialization, deallocation or custom accessor methods, as described later in this section.

You Can Customize Synthesized Instance Variable Names

As mentioned earlier, the default behavior for a writeable property is to use an instance variable called _propertyName.

If you wish to use a different name for the instance variable, you need to direct the compiler to synthesize the variable using the following syntax in your implementation:

@implementation YourClass
@synthesize propertyName = instanceVariableName;
...
@end

For example:

@synthesize firstName = ivar_firstName;

In this case, the property will still be called firstName, and be accessible through firstName and setFirstName: accessor methods or dot syntax, but it will be backed by an instance variable called ivar_firstName.

Important: If you use @synthesize without specifying an instance variable name, like this:

@synthesize firstName;

the instance variable will bear the same name as the property.

In this example, the instance variable will also be called firstName, without an underscore.

You Can Define Instance Variables without Properties

It’s best practice to use a property on an object any time you need to keep track of a value or another object.

If you do need to define your own instance variables without declaring a property, you can add them inside braces at the top of the class interface or implementation, like this:

@interface SomeClass : NSObject {
    NSString *_myNonPropertyInstanceVariable;
}
...
@end
 
@implementation SomeClass {
    NSString *_anotherCustomInstanceVariable;
}
...
@end

https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/DeclaredProperty.html#//apple_ref/doc/uid/TP40008195-CH13-SW1

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW2

oc的属性的更多相关文章

  1. iOS runtime探究(三): 从runtime開始理解OC的属性property

    你要知道的runtime都在这里 转载请注明出处 http://blog.csdn.net/u014205968/article/details/67639303 本文主要解说runtime相关知识, ...

  2. OC中属性及方法

    1.声明式属性    a.实例变量    b.声明属性        自动生成setter/getter方法        .h ->@property 属性类型 属性名;        .m ...

  3. OC:属性的内部实现原理、dealloc内释放实例变量、便利构造器方法的实现原理、collection的内存管理

    代码: // // main.m #import <Foundation/Foundation.h> #import "Person.h" #import " ...

  4. OC:属性、点语法、KVC

    //属性的属性 属性定义在一个 .h文件里,在这个.h文件里可以定义实例变量(就是这个类的特征),也可以通过   @protery(属性约束关键字) 属性名字类型 属性名 来定义一些属性,在prope ...

  5. swift和oc区别----属性部分(参考官方swift2.1文档)

    对于实用过OC的人来说实用swift上手时非常容易的,swift包括了oc的大部分功能,但是swift毕竟是一门新的编程语言,它和OC还是 有很多不同的地方,而且提供了不少新功能,所以本人在读swif ...

  6. OC中属性readwrite,readonly,assign,retain,copy,nonatomic 各是什么作用,在那种情况下用?

    此次只做简单说明,不做代码演示! 1> readwrite:同时生成get方法和set方法的声明和实现 2> readonly:只生成get方法的声明和实现 3> assign:se ...

  7. OC基础:属性.点语法.KVC 分类: ios学习 OC 2015-06-24 17:24 61人阅读 评论(0) 收藏

    属性:快速生成setter和getter 属性也包括:声明和实现 1.属性的声明写在.h中 格式:@property 数据类型 变量名; 如果实例变量一致的时候,属性的声明可以合并,每一个属性之间使用 ...

  8. html5 请求的URL转成 OC可用属性字符串显示

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:helpUrlStr]]; NSString *string = [ ...

  9. 张超超OC基础回顾01_类的创建,申明属性,以及本质

    一. 类的声明和实现&规则 1.如何编写类的声明 以@interface开头 , 以@end结尾, 然后再class name对应的地方写上 事物名称, 也就是类名即可 注意: 类名的首字符必 ...

随机推荐

  1. DOM学习之图片库切换效果

    addloadevent(prepareplaceholder()) addloadevent(prepareGallery()) //页面加载完时执行函数 function addloadevent ...

  2. luogu P4512 多项式除法 (模板题、FFT、多项式求逆)

    手动博客搬家: 本文发表于20181206 14:42:53, 原地址https://blog.csdn.net/suncongbo/article/details/84853342 题目链接: ht ...

  3. 痛苦的Windows下的temp目录

    2007不能运行了,错误: [MSBuild Error] “DCC”任务意外失败. System.Configuration.ConfigurationErrorsException: 配置系统未能 ...

  4. 【ZOJ 4062】Plants vs. Zombies

    [链接] 我是链接,点我呀:) [题意] [题解] 二分最后的最大抵御值mid. 然后对于每个蘑菇. 都能算出来它要浇水几次mid/ai 然后如果第i个蘑菇没浇水达到要求次数. 就在i和i+1之间来回 ...

  5. 图论·Floyd算法·HDU2544&1874 (伪)2066

    在看到1874的题时,第一反应是用上一篇的并查集方法,后来查了一下是要用Floyd做,所以就去查Floyd算法的资料. 即插点法,是一种用于寻找给定的加权图中顶点间最短路径的算法. 核心代码:  ma ...

  6. ul,li不能左右居中的问题

    近期帮朋友做一个他们公司的商品站点,用到了曾经学到的html+css技术,当然做站点少不了Javascript和jquery这些..... 这个功能主要实现了导航条里面的条目是居中的.所以声明了ul, ...

  7. POJ 2029

    二维树状数组可解此题 #include <iostream> #include <cstdio> #include <cstring> #include <a ...

  8. HDU 1429--胜利大逃亡(续)【BFS &amp;&amp; 状态压缩】

    胜利大逃亡(续) Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total S ...

  9. 面向基于英特尔&#174; 架构的 Android* 的 CoCos2D

    Cocos2D 是一款游戏引擎,可与从电脑到手机等多种设备配合使用. 该引擎支持丰富的特性,可帮助创建出色的 2D 游戏.它甚至包含具备全面功能的物理引擎. CoCos2D 的核心元素是基本动画元素( ...

  10. C++研究之在开发中你可能没有考虑到的两个性能优化

     1:多余的存储引用导致性能减少. 2:利用局部性提高程序性能: 先来说说引用是怎么减少程序性能.个人觉得减少程序性能主要有两个原因,一是数据结构选择不合理,二是多层嵌套循环导致部分代码被多余反复 ...