zz object c

 

Objective-C中,咱们能够用new简单的代替alloc init,咱们今天介绍的是相似于new这种简易用法的另外一种OC特性,用@property,@synthesize来代替get,set方法,用起来很简单,能够省掉不少的代码量,当须要用SET,GET方法的地方,咱们能够用@property,@synthesize来简单的代替,这时系统会自动给咱们生成该变量的set,get方法,@property对应方法的声明部分,@synthesize对应方法的实现部分。java

这时系统会自动生成age,height的set,get方法,能够直接使用,那还有一种状况,若是我只想让age有get方法,没有set方法怎么办,也就是说在初始化里给一个默认值,而这个值只能被调用,不能被修改,用@property这种方式能够吗?答案是确定的,由于@property给咱们提供了相似参数的一种可选项,关键词是readonly,readwrite,分别对应着只能读不能修改和读写都可,通常咱们不设置readwrite,由于默认就是读写状态。看代码:objective-c

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

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

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


#import <Foundation/Foundation.h> 
@class AnotherClass;
@interface TestClass : NSObject { it

int  age; 

NSString  *name; io

}class

-(void)  doMethod1;
-(void)  doMethod3: (NsString *)str withAnotherPara:(float) value; 
+(void)  doMethod4; import

-(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]; 

相关文章
相关标签/搜索