Objective-C语言-点语法和变量作用域-@property @synthesize和id

时间 : 15-09-14 栏目 : iOS, 移动开发 作者 : noway 评论 : 0 点击 : 458 次

一、点语法

(一)认识点语法

声明一个Person类:

bubuko.com,布布扣

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    int _age;//默认为@protected
}

- (void)setAge:(int)age;
- (int)age;

@end

View Code

    Person类的实现:

bubuko.com,布布扣

#import "Person.h"

@implementation Person

- (void)setAge:(int)age
{
    _age = age;// 不能写成self.age = newAge,相当与 [self setAge:newAge];
}

- (int)age  //get方法
{
    return _age;
}

@end

View Code

点语法的使用:

bubuko.com,布布扣

#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        Person *person = [[Person alloc] init];
        
        //[person setAge:10];
        person.age = 10;//语法,等效与[person setAge:10];
//这里并不是给person的属性赋值,而是调用person的setAge方法
        
        //int age = [person age];
        int age = person.age;//等效与int age = [person age]
       NSLog(@"age is %i", age);
        [person release];
        
    }
    return 0;
}

View Code

(二)点语法的作用

OC设计点语法的目的,是为了让其他语言的开发者可以很快的上手OC语言开发,使用点语法,让它和其他面向对象的语言如java很像。

(三)点语法的本质

语法的本质是方法的调用,而不是访问成员变量,当使用点语法时,编译器会自动展开成相应的方法。切记点语法的本质是转换成相应的set和get方法,如果没有set和get方法,则不能使用点语法。

如:

Stu.age=10;展开为:[stu setAge:10];

int  a=stu.age;展开为:[stu age];

编译器如何知道是set方法还是get方法?主要是看赋值(可以使用断点调试来查看)。

在OC中访问成员变量只有一种方式即使用-> 如stu->age,这种情况要求在@public的前提下。

(四)点语法的使用注意

下面的使用方式是一个死循环:

   (1)在set方法中,self.age=age;相当于是[self setAge:age];

(2)在get方法中,return self.age;相当于是[self age];

二、变量作用域

(一)变量的作用域主要分为四种:

(1)@public (公开的)在有对象的前提下,任何地方都可以直接访问。

(2)@protected (受保护的)只能在当前类和子类的对象方法中访问

(3)@private (私有的)只能在当前类的对象方法中才能直接访问

(4)@package (框架级别的)作用域介于私有和公开之间,只要处于同一个框架中就可以直接通过变量名访问

(二)使用注意和补充

(1)在类的实现即.m文件中也可以声明成员变量,但是因为在其他文件中通常都只是包含头文件而不会包含实现文件,所以在这里声明的成员变量是@private的。在.m中定义的成员变量不能喝它的头文件.h中的成员变量同名,在这期间使用@public等关键字也是徒劳的。

(2)在@interface  @end之间声明的成员变量如果不做特别的说明,那么其默认是protected的。

(3)一个类继承了另一个类,那么就拥有了父类的所有成员变量和方法,注意所有的成员变量它都拥有,只是有的它不能直接访问。

 

三、@property @synthesize关键字

注意:这两个关键字是编译器特性,让xcode可以自动生成getter和setter的声明和实现。

(一)@property 关键字

@property 关键字可以自动生成某个成员变量的setter和getter方法的声明

@property int age;

编译时遇到这一行,则自动扩展成下面两句:

- (void)setAge:(int)age;

- (int)age;

(二)@synthesize关键字

@synthesize关键字帮助生成成员变量的setter和getter方法的实现。

语法:@synthesize age=_age;

相当于下面的代码:

- (void)setAge:(int)age

{

_age=age;

}

- (int)age

{

Return _age;

}

(三)关键字的使用和使用注意

类的声明部分:

 bubuko.com,布布扣

类的实现部分:

 bubuko.com,布布扣

测试程序:

 bubuko.com,布布扣

新版本中:

类的声明部分:

 bubuko.com,布布扣

类的实现部分:

 bubuko.com,布布扣

测试程序:

 bubuko.com,布布扣

(1)在老式的代码中,@property只能写在@interface  @end中,@synthesize只能写在@implementation   @end中,自从xcode 4.4后,@property就独揽了@property和@synthesize的功能。

(2)@property int age;这句话完成了3个功能:1)生成_age成员变量的get和set方法的声明;2)生成_age成员变量set和get方法的实现;3)生成一个_age的成员变量。

注意:这种方式生成的成员变量是private的。

(3)可以通过在{}中加上int _age;显示的声明_age为protected的。

(4)原则:get和set方法同变量一样,如果你自己定义了,那么就使用你已经定义的,如果没有定义,那么就自动生成一个。

(5)手动实现:

1)如果手动实现了set方法,那么编译器就只生成get方法和成员变量;

2)如果手动实现了get方法,那么编译器就只生成set方法和成员变量;

3)如果set和get方法都是手动实现的,那么编译器将不会生成成员变量。

 bubuko.com,布布扣

四、Id

id 是一种类型,万能指针,能够指向\操作任何的对象。

注意:在id的定义中,已经包好了*号。Id指针只能指向os的对象。

id 类型的定义

Typedef struct objc object{

Class isa;

} *id;

局限性:调用一个不存在的方法,编译器会马上报错。

本文标签

除非注明,文章均为( noway )原创,转载请保留链接: http://blog-old.z3a105.com/?p=540

Objective-C语言-点语法和变量作用域-@property @synthesize和id:等您坐沙发呢!

发表评论





       ==QQ:122320466==

 微信    QQ群


0

Aujourd’hui, une partie avec le développement du e-commerce, achats en ligne est devenu une partie de la vie pour beaucoup de gens. La mariage a commencé achats en ligne. Si vous choisissez achats les mariages en ligne, il peut être beaucoup moins cher que le salon de la Robe de mariée pas chermariée local, réduisant le budget de mariage. vous pouvez avoir beaucoup de choix si acheter de mariage en ligne. vous pouvez ramasser une robe de mariée bon marché sur Internet.
Piercing fascinerande figur, och nu tittar vi på 2016 senast brudklänning, kan du vara den vackraste bruden det!2016 senaste Bra brudklänning, söt temperament Bra design, romantiska spetsar blomma kjol, som du lägger till en elegant och charmig temperament.Kvinnan tillbaka mjuka linjer, människor brudklänningofta få en känsla av oändlig frestelse. Fall 2016 mässan, lämnar uppgifter om ditt bröllop charmig.
Yesterday afternoon, the Chinese team was training in the Guangzhou Gymnasium, when the reporter asked Zhao Yunlei the feeling of wearing the new cheap jersey , cheap jerseys online shopshe readily took a shirt from the bag crumpled ball to reporters, and she said with a smile: ” This shirt is light. ”Zhao Yunlei said: “Our material is very light like with the clothes of the tennis King Nadal, Federer, after the sweat, sweat does not drip down to the ground, when we do move, it is easy pace slipping if the sweat drip on the floor.”Tennis players Zhang Yawen, told reporters: “You might think the clothes attached to the body, fearing we swing will be affected, in fact, we do not feel anything, because the clothes are very light, very soft, put on quite comfortable. And it’s particularly good clothes to dry, washing and will dry in 15 minutes. ”
China’s sports enthusiasts NFL sweatshirt with mad love and the pursuit of, and therefore, NFL jerseys have a good market in China and development. China is a populous country, is the consumer, the economic momentum is so good, the sales prospects sportswear is immeasurable. With hot sales sweatshirt, but also to promote the importance of sports fans, on health, on the other hand is a matter of concern for the World Cup, fans wearing NFL jerseys and also can express themselves more fully love and obsession Therefore, NFL jerseys Wholesale jerseys online shopwholesale has good prospects and development in China.
ANTA-ANTA Sports Products Limited, referred to as ANTA Sports, Anta, is China’s leading sporting goods companies, mainly engaged in the design, development, manufacture and marketing of ANTA brand sporting goods, including sports footwear, apparel and accessories. Anta sweatshirt design advantages, warm stretch knit fabric, using Slim version of model, more personal fit, bid farewell to bloated, so wearing more stylish.GUIRENNIAO-This logo is a spiritual totem, smooth graphics implication unstoppable force; flexible deliver an elegant arc Wholesale jerseys china shop movement, strength and speed of the United States, a symbol of passion and rationality publicity “Heart” and “meaning”, “concept” unity; pass the fearless and enterprising mind, showing beyond the realm of self, to unstoppable force to create the future.XTEP-Xtep (China) Co., Ltd. is a comprehensive development wholesale jerseys china shop, production and marketing of Xtep brand (XTEP) sports shoes, clothing, bags, caps, balls, socks mainly large sporting goods industry enterprises.
There are a lot of fans in identifying the authenticity of the above cheap jerseys have great distress, so here to i will show you some methods to definitely affordable inexpensive cheap jerseys : Firstly, we should look at if it is working fine. China has been called the world’s factory, a lot cheap jerseys factories in China have foundries, but our cheap jerseys are all from here! Secondly, should to see whether it is the , we all know that it is difficult to get out of print once a genuine cheap cheap jerseys free shipping jersey was print. and we have all kind of stocka on the whole website, in other words, we have all you want ! Finally, look at the price, our price is not necessarily the lowest in the whole website but it must be most fair on the whole website, we certainly you will not regret later when you buy it. Of course, except that cheap jerseys, we also have the other products, such as socks, leggings and some other related products, everyone can enjoy the best services of here!

KUBET