#import "D.h"
@interface A : NSObject
{
BOOL myBoolValue1; //在这里声明的,叫做成员变量(member variable),如果单单是在{}里声明而没有@property的话,
//这个变量只能在类内部访问
BOOL myBoolValue2;
D *myValue3;
D *myValue4;
}
//在@interface括号中定义一个变量并用@property 重复定义一次是很普遍的,实际上不是必要的。用@property和@synthszie就够了,
//因为在用@synthsize合成这个属性的读写方法时就会创建一个变量。
@property(nonatomic, readwrite, assign) BOOL boolValue1; //公有布尔变量 , 在.h里面使用@property的变量就可以被外部类调用了
@property(nonatomic, readwrite, retain) D *value3; //公有对象指针
- (void)function1; //公有函数的声明
@end
#import "A.h"
NSString *const string1 = @"abc"; //一些常量字符串的定义
NSString *string2 = @"aaaaa"; //一些字符串的定义
static B *b = nil; //B类指针的定义
typedef enum
{
CSIPhoneVideo,
CSIPadVideo
}CSMode; //私有枚举变量定义
#define kSIdefault 0 //宏定义
class C : public D
{
public:
C() {};
}; //C++类
extern "C"
{
........
........
}
@interface A()
- (void)fuction2; //私有函数的声明
@property (nonatomic, readwrite, assign) BOOL boolValue2; //私有变量的property是在.m文件里写的
@property (nonatomic, readwrite, retain) D *value4; //私有变量
@end
@implementation A
//@synthsize gameCenter = _gameCenter;
//默认情况下,SDK已经为gameCenter设置了一个同样名字的变量,但如果你要设置不同名字的变量则使用这种方法
//gameCenter 属性,说明了不管什么值被分配给这个属性,都会存储到_gameCenter这个变量中。
//据千锋的第2节语法课课程的讲解,这样写之后可以使得 @synthsize 时内部getter方法会展成
1 -(int)gameCenter 2 { 3 return _gameCenter; 4 }
而直接写 @synthsize gameCenter;
setter函数会在内部展开成
1 -(int)gameCenter 2 { 3 return gameCenter; 4 }
注意到:函数名和变量名是一样的。在斯坦福的课程中,白胡子教授也模糊的说道这样的同名有可能带来bug,具体什么bug他没说,我也没见过,所以还是养成这样写的习惯为好。其他语言的getter函数 一般会在变量前加 get;但oc没有,可能是为了与其他语言做区分,算是oc的特色,结果却带来这么个麻烦。
@synthesize boolValue1 = myBoolValue1;
@synthesize boolValue2 = myBoolValue2;
@synthesize value3 = myValue3;
@synthesize value4 = myValue4;
//初始化函数
- (id)init
{
self = [super init];
if (self != nil)
{
self.boolValue1 = NO;
self.boolValue2 = NO;
}
}
//公有函数实现
- (void)function1
{
//分配空间时用myXXX = [[XXXXX alloc] init];
myValue3 = [[D alloc] init];
myValue4 = [[D alloc] init];
//赋值时用self.XXX = XXXXX,如果使用了ARC的话,用不用self.都一样的
self.value3 = self.value4;
self.boolValue1 = self.boolValue2;
}
//私有函数实现
- (void)function2
{
........
}
- (void)dealloc
{
//assign类型的变量就不用在这玩了,因为没有引用计数的加减
//有alloc过的变量,注意这里的用法,都是用到my,如果没有设置my的话,就直接用[value3 release], 不能用[self.value3 release]
if (myValue3 != nil)
{
[myValue3 release];
myValue3 = nil;
}
if (myValue4 != nil)
{
[myValue4 release];
myValue4 = nil;
}
[super dealloc];
}
@end