zoukankan      html  css  js  c++  java
  • Objective-C NSString基本使用 类方法 self关键字

    NSString基本使用 

    #import <Foundation/Foundation.h>
    
    int main() {
        //最简单的创建字符串的方式
        NSString *str = @"大武汉";
        NSLog(@"我在%@", str);
        
        //另一种创建字符串的方式
        int age = 15;
        int no = 5668;
        NSString *name = @"黄祎a";
        NSString *newStr = [NSString stringWithFormat : @"My age is %i and My no is % i and My name is %@", age, no, name];
        NSLog(@"---------%@", newStr);
        
        //获取字符串的长度
        int size = [name length];
        NSLog(@"名字的长度是%i", size);
        return 0;
    }

    类方法

    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject
    + (void) test;
    @end
    
    @implementation Person
    + (void) test {
        NSLog(@"hello world");
    }
    @end
    
    int main() {
        [Person test];
        return 0;
    }
    
    /*
     对象方法
        以 - 开头 <只能>由对象调用
        对象方法可以使用成员变量
        相对而言效率低
     
     类方法
        以 + 开头 <只能>由类调用
        类方法不能使用成员变量
        相对而言效率高
     
     一个类中允许出现对象方法名 = 类方法名
     */ 

    self关键字

    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject {
        @public
        int _age;
    }
    - (void) show;
    - (void) test1;
    - (void) test2;
    @end
    
    @implementation Person
    - (void) show {
        NSLog(@"Person的年龄是%i", _age);
    }
    - (void) test1 {
        int _age = 20;
        NSLog(@"Person的年龄是%i", _age);
    }
    - (void) test2 {
        int _age = 30;
        NSLog(@"Person的年龄是%i", self->_age);
    }
    @end
    
    int main() {
        Person *p = [Person new];
        [p show];
        [p test1];
        [p test2];
        return 0;
    }
    
    //当成员变量和局部变量同名 采取就近原则 访问的是局部变量
    //用self可以访问成员变量 区分成员变量和局部变量
    
    /** 使用细节 **/
    //出现的地方: 所有OC方法中(对象方法|类方法) 不能出现在函数中
    //作用: 使用'self->成员变量名'访问当前方法调用的成员变量; 使用'[self 方法名]'用来调用方法(对象方法|类方法)
    
    /** 常见错误 **/
    //用self去调用函数
    //类方法中使用self调用对象方法 对象方法中使用self调用类方法
    //self死循环
  • 相关阅读:
    hash联接算法
    Nginx实现WEB故障转移以及重定向
    MSSQL分区表
    SSO示例
    MSMQ 跨服务器读写队列
    利用Heartbeat完成Mysql主-主同步
    采用heartbeat做Redis的主从切换
    Redis的RDB AOF DATABASE
    Redis初试
    简单线性回归
  • 原文地址:https://www.cnblogs.com/huangyi-427/p/4597738.html
Copyright © 2011-2022 走看看