zoukankan      html  css  js  c++  java
  • zz object c

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

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

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

  • 相关阅读:
    hash
    DatabaseLibrary -数据库操作
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 18-22: ordinal not in range(128)
    robotframework_酷我音乐_That Girl
    robotframework_百度登陆
    12306_车票预定_修改日期
    基础知识:索引和分片
    基础知识:字符串
    基础知识: 常用数据类型分类 及 数值
    c++拷贝构造函数
  • 原文地址:https://www.cnblogs.com/liangouyang/p/7050942.html
Copyright © 2011-2022 走看看