当前位置:首页 > 百科中心 > IT技术 > 客户端技术

Object-C中的类方法和实例方法区别

Object-C中方法的概念和Java一样,Object-c中有两种方法—实例方法(需要实例化才能调用的方法)和类方法(类方法也可以说是静态方法,参照Java中的静态方法)。

     声明实例方法需要在减号字符(-)作为前缀。声明类方法需要使用加号字符(+)作为前缀。 在Object-c中方法需要在头文件中声明,方法声明示例: 

 

 

#import <Foundation/Foundation.h> 

@class AnotherClass;

@interface TestClass : NSObject { 

 

 int  age; 

NSString  *name; 

}

-(void)  doMethod1;

-(void)  doMethod3: (NsString *)str withAnotherPara:(float) value; 

+(void)  doMethod4; 

 

-(void)  doMethod2: (NSString *)str; 

 

@end 

 

方法实现示例: 

#import “TestClass.h” 

 

@implementation TestClass 

 

-(void)  doMethod1{ 

    --(方法主体)-- 

 

 

-(void)  doMethod2:(NSString *) str{ 

    --(方法主体)-- 

 

 

-(void)  doMethod3:(NSString *) str withAnotherPara:(float)  value { 

    --(方法主体)-- 

 

 

+(void) doMethod4 { 

 

    --(方法主体)-- 

 

 

 

调用方法示例: 

TestClass *justTest =[TestClass alloc]; 

 

[justTest doMethod1]; 

[justTest doMethod2 : @”Holle Xiaming”]; 

[justTest doMethod3 : @”Holle xiaming”withAnotherPara:1.0f]; 

 

//类方法可直接使用类名调用// 

 

[TestClass doMethod4]; 


【云广告】
本文章由网友发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

评论