设为首页 加入收藏

TOP

Object C学习笔记10-静态方法和静态属性(一)
2014-11-23 18:53:34 】 浏览:8150
Tags:Object 学习 笔记 10- 静态 方法 属性
 在.NET中我们静态使用的关键字static有着举足轻重的作用,static 方法可以不用实例化类实例就可以直接调用,static 属性也是如此。在Object C中也存在static关键字,今天的学习过程使用到了这个关键字,在这里记录一下static的使用。
  在Object C的语法中声明后的static静态变量在其他类中是不能通过类名直接访问的,它的作用域只能是在声明的这个.m文件中 。不过可以调用这个类的方法间接的修改这个静态变量的值。对于Object C中的类使用和定义在前面已经做过相应的记录,可以查看Object C学习笔记3-对象的使用和定义。
  1. 静态属性
  Object C中静态属性的定义和.NET中的有点不一样,先看看如下代码:
复制代码
#import
@interface Person : NSObject
{
int age;
NSString *name;
static int totalCount;
}
@property int age;
@property NSString *name;
-(void) write;
+(void) hello;
@end
复制代码
  以上代码定义 static int totalCount; 这样在编译器中编译会报错,这样的代码编写对于编译器是不认可的。正确的定义放入如下:
复制代码
#import
@interface Person : NSObject
{
int age;
NSString *name;
}
@property int age;
@property NSString *name;
-(void) write;
+(void) hello;
@end
复制代码
复制代码
#import "Person.h"
static int count;
@implementation Person
@synthesize age;
@synthesize name;
-(void) write
{
NSLog(@"姓名:%@ 年龄:%i",name,age);
}
+(void) hello
{
count++;
NSLog(@"static = %i",count);
}
@end
复制代码
  static 属性应该定义在implementation中,而且写在implementation之外或者方法之中。以上代码是将static 属性写在implementation之外。
复制代码
@autoreleasepool {
for(int i=0;i<5;i++){
[Person hello];
}
}
测试结果
2014-02-15 22:03:14.642 Object11[488:303] static = 1
2014-02-15 22:03:14.644 Object11[488:303] static = 2
2014-02-15 22:03:14.644 Object11[488:303] static = 3
2014-02-15 22:03:14.645 Object11[488:303] static = 4
2014-02-15 22:03:14.645 Object11[488:303] static = 5
复制代码
  从以上代码可以看出,调用hello方法直接使用类名Person而非Person的实例,而且每次调用之后count都会+1.
  2. static属性在方法中
  修改代码如下,将static属性改到方法中。
复制代码
#import "Person.h"
@implementation Person
@synthesize age;
@synthesize name;
-(void) write
{
NSLog(@"姓名:%@ 年龄:%i",name,age);
}
+(void) hello
{
static int count;
count++;
NSLog(@"static = %i",count);
}
复制代码
  使用如上方式和1中的效果一样,static属性是属于类全局的,看看测试代码就知道效果如何:
复制代码
@autoreleasepool {
for(int i=0;i<5;i++){
[Person hello];
}
}
//测试结果
2014-02-15 22:12:04.681 Object11[528:303] static = 1
2014-02-15 22:12:04.683 Object11[528:303] static = 2
2014-02-15 22:12:04.684 Object11[528:303] static = 3
2014-02-15 22:12:04.685 Object11[528:303] static = 4
2014-02-15 22:12:04.685 Object11[528:303] static = 5
复制代码
  效果和前面的是一样的。下面再看看在实例方法中定义static 属性看看效果如下,修改代码如下:
复制代码
#import "Person.h"
@implementation Person
@synthesize age;
@synthesize name;
-(void) write
{
static int myage=0;
myage++;
NSLog(@"年龄:%i",myage);
}
+(void) hello
{
static int count;
count++;
NSLog(@"static = %i",count);
}
复制代码
  测试实例方法中的静态属性测试方法如下:
复制代码
@autoreleasepool {
for(int i=0;i<5;i++){
Person *p=[[Person alloc] init];
p.name=[NSString stringWithFormat:@" %@ %i",@"object c",i];
[p write];
}
}
//测试结果如下
2014-02-15 22:20:35.161 Object11[582:303] 姓名: obj
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇和GUI有关的各种对象 下一篇c语言进阶总结1

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目