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

Objectiva C 学习笔记2-

2012年02月08日 ⁄ 综合 ⁄ 共 1035字 ⁄ 字号 评论关闭

1. 关于实例方法内self的使用, ObjC比较特殊. 比如下例子, self.name 实际上会访问 property name,而不是直接访问内部变量,也就是说会访问 setter/getter方法,需要注意

 

@interface Person : NSObject
{
   NSString 
*name;
}
@property (copy) NSString 
*name;
@end

@implementation Person
-(void) doSomething {
name 
= @"Fred"// access ivar directly!
self.name = @"fred"// calls accessor method.
}
@sythesize name;
@end

 .h文件,声明类, 大括号以内是私有变量

 

#import <Foundation/Foundation.h>
@interface Person: NSObject
{
// instance variables
NSString *name;
int age;
}
// method declarations
- (NSString *)name;
- (void)setName:(NSString *)value;

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

- (BOOL)canLegallyVote;
- (void)castBallot;
@end

 

实现类

 

#import "Person.h"

@implementation Person
- (int)age {
return age;
}
- (void)setAge:(int)value {
age 
= value;
}
//... and other methods like super.init();
@end

对象创建有2步,+alloc 和-init, 前者是内存分配(需要release)后者是进行初始化。

-retain 是增加计数

-release 是减少计数

-dealloc 系统会自动调用当 retain count 为0时候

[nil doSomething]; 没反应的方法

@property (assign) NSString *name; // pointer assignment
@property (retain) NSString *name; // retain called
@property (copy) NSString *name; // copy called

 

 

抱歉!评论已关闭.