现在的位置: 首页 > 综合 > 正文

oc 面向对象特性(属性,构造方法)

2017年10月24日 ⁄ 综合 ⁄ 共 1984字 ⁄ 字号 评论关闭

属性

在上一小节中对于成员变量的访问,要通过读取方法(getter)和设定方法(setter)。在实现部分也要实现这些读取方法和设定方法,为了简化这些琐碎编码Objective-C2.0提出属性的概念,使用@property关键字在接口部分定义属性,在实现部分使用@synthesize关键字在组装和合成这些属性。 

Song.h文件:

@interface Song : NSObject {
       NSString *title;
       NSString *artist;
       long int duration;
}
//操作方法
- (void)start;
- (void)stop;
- (void)seek:(long int)time;
//访问成员变量方法
@property(copy,readwrite) NSString *title; 
@property(nonatomic,retain) NSString *artist; 
@property(readonly) long int duration;
@end


说明:

声明property的语法为:@property (参数) 类型 名字;,这里的“参数”主要分为3大类:


读写属性(readwrite/readonly);


内存管理(assign/retain/copy),这些内存管理的参数,我们将在内存管理小节部分介绍;


原子性atomicity(nonatomic),是关系线程线程安全的,atomicity是原子性的线程安全的,但是会影响性能。如果确定不考虑线程安全问题可以使用nonatomic。 

Song.m文件:

@implementation Song
@synthesize title;
@synthesize artist;
@synthesize duration;
- (void)start { //开始播放
}
- (void)stop {}
//停止播放
- (void)seek:(long int)time {}
//跳过时间 @end

构造方法

出于初始化类中的成员变量的需要,可以提供一个方法用于此目的,这个方法就叫构造方法或构造方法(Constructor)。与C++和Java不同,Objective-C命名是没有限制的,并且有返回值本身类型指针。 

Song.h文件:

@interface Song : NSObject {
       NSString *title;
       NSString *artist;
       long int duration;
}
//操作方法
- (void)start;
- (void)stop;
- (void)seek:(long int)time;
//访问成员变量方法
@property(nonatomic,retain) NSString *title; 
@property(nonatomic,retain) NSString *artist; 
@property(readwrite) long int duration; 
//构造方法
-(Song*) initWithTitle: (NSString *) newTitle andArtist: (NSString *) newArtist andDuration:(long int) newDuration;
@end

说明:

在Song类的定义中添加了一个方法,它一般用init开头命名,它的返回值很特殊,是返回值本身类型指针。并且有返回值本身类型指针。 

Song.m文件:

@implementation Song
@synthesize title;
@synthesize artist;
@synthesize duration;
//构造方法
-(Song*) initWithTitle: (NSString *) newTitle
              andArtist: (NSString *) newArtist
                    andDuration:(long int)newDuration {
       self = [super init];
       if ( self ) {
               self.title = newTitle;
               self.artist = newArtist;
               self.duration = newDuration;
       }
       return self;
}
... ...
@end

说明:

构造方法的实现几乎就是模式方法,基本上就是如下写法:

self = [super init];
if ( self ) {
...... }
return self;

说明:

 其中使用[super
init]来调用父类默认构造方法。这个
方法返回的实例对象指派给另一新个关键词:self。self很像 C++ 和 Java 的 this。


还有if ( self ) 跟 ( self != nil ) 一样,是为了确定调用父类构造方法成功返回了一个新对象。当初始化变量以后,用返回self 的方式来获得自己的地址。


父类默认构造方法 -(id) init。技术上来说,Objective-C中的构造方法就是一个 "init" 开头的方法,而不像 C++ 与
Java 有特殊的结构。 

抱歉!评论已关闭.