object c 基础语法ios相关点

objectve-C语法总结<1>

2015-12-02  本文已影响252人  天天想念

大纲



0.OC中的数据类型

关键字 数据类型
int: 声明整型变量
double: 声明双精度变量
float: 声明浮点型变量
char: 声明字符型变量
id: 通用的指针类型
enum: 声明枚举类型
long: 声明长整型变量或函数
short: 声明短整型变量或函数
signed: 声明有符号类型变量
struct: 声明结构体变量
union: 声明共用体(联合)数据类型
unsigned: 声明无符号类型变量
void: 声明函数无返回值或无参
数据类型 oc关键字 格式说明引导符
整型 int %d.%i
短整型 short int %hd.%hi
长整型 long int %ld.%li
无符号短整型 unsigned int %u
无短整型 unsigned short %hu
无符号长整型 unsigned long %lu
浮点型 float %f
双精度型 double %f
长双精度型 long double %lf
字符型 char %c
#import <Foundation/Foundation.h>  
  
int main(int argc, const char * argv[])  
{  
  
    @autoreleasepool {  
          
        //保留字是不能定义为变量名的,例如下面的int、float等就不能作为变量名  
        int i = 2;  
        float f = 2.3f;  
        double d = 2.3e12;  
        char c = 'a';  
          
        //输出数据  
        NSLog(@"i : %d",i);  
        NSLog(@"f : %f 截取后 : %.2f",f,f);  
        NSLog(@"d : %e 截取后 : %.2e",d,d);  
        NSLog(@"c : %c , %d",c ,c );  
          
        //数据转换  
        //数据类型容量大的转成小的可能会丢失精度  
        int i2 = (int)f;  
        float f2 = (float)i ;  
          
        NSLog(@"数据转换");  
        NSLog(@"i2 : %d",i2);  
        NSLog(@"f2 : %f",f2);  
          
        NSLog(@"变量的作用域");  
        if(YES){  
            int i3 = 2;  
             NSLog(@"i3 : %d",i3);  
        }  
        //在if的{}外面是无法访问到内部的i3变量的,因为i3变量的作用域就只是那对{}内部  
        //NSLog(@"i3 : %d",i3);  
        /*  
         运行结果  
         [859:303] i : 2  
         [859:303] f : 2.300000 截取后 : 2.30  
         [859:303] d : 2.300000e+12 截取后 : 2.30e+12  
         [859:303] c : a , 97  
         [859:303] 数据转换  
         [859:303] i2 : 2  
         [859:303] f2 : 2.000000  
         */  
    }  
    return 0;  
}  

1.声明一个类


2.实现一个类

@implementation MyClass

// 对象方法
- (id)initWithString:(NSString *)aName
{
    //TODO
}

// 类方法
+ (MyClass *)myClassWithString:(NSString *)aName
{
    //TODO
}

@end

3.创建一个对象

4.对象的注意点

5.对象方法

5.1.对象方法的声明

@interface MyClass : NSObject

//声明没有返回值的方法
- (void)method;
//声明有返回值的方法
- (int)newMethod;
//声明有返回值有参数的方法
- (int)method: (int)var;
//声明有返回值有多个参数的方法
- (int)method: (int)var1 andVar2: (int)var2;

@end

5.2.对象方法实现

@implementation MyClass

//声明没有返回值的方法
- (void)method{
    // TODO
}
//声明有返回值的方法
- (int)newMethod{
    // TODO
    return 10;
}
//声明有返回值有参数的方法
- (int)method: (int)var{
    // TODO
    return 20;
}
//声明有返回值有多个参数的方法
- (int)method: (int)var1 andVar2: (int)var2{
    // TODO
    return 30;
}

@end

6.类方法

6.1.类方法声明

//声明没有返回值的方法
+ (void)method;
//声明有返回值的方法
+ (int) newMethod;
//声明有返回值有参数的方法
+ (int)method: (int)var;
//声明有返回值有多个参数的方法
+ (int)method: (int)var1 andVar2: (int)var2;

6.2.类方法实现

//声明没有返回值的方法
+ (void)method{
    // TODO
}
//声明有返回值的方法
+ (int)newMethod{
    // TODO
    return 10;
}
//声明有返回值有参数的方法
+ (int)method: (int)var{
    // TODO
    return 20;
}
//声明有返回值有多个参数的方法
+ (int)method: (int)var1 andVar2: (int)var2{
    // TODO
    return 30;
}

6.3.对象方法和类方法区别

7.getter/setter方法

@interface MyClass()
{
    // 定义一个NSString(字符串)类型的属性Name
    NSString *Name;
}
@end

@implementation MyClass

// setter方法
- (void)setName:(NSString *)name{
    Name = name;
}

// getter方法
- (NSString *)name{
    return name;
}
@end

8.点语法

8.1点语法的本质

8.2点语法注意点

- (void) setAge:(int)age {
    // 下面的代码会引发死循环
    self.age = age;
    //编译器展开后 [self setAge:age]
}


- (int) age {
    // 下面的代码会引发死循环
    return self.age;
    // 编译器展开后 [self   age]
}

9.self关键字

总结

10.OC中的继承

10.1继承语法

@interface 子类名称 : 父类名称

@end

10.2方法重写

- (void)viewDidLoad {
    // 调用父类的viewDidLoad方法。
    [super viewDidLoad];
    // 在重写方法中做一些操作
    NSLog(@"%@",@"my first iOS project");
    
}

11.super关键字

12.OC中的多态

Animal *animal = nil;

//实例化猫的对象
animal = [Cat new];
[animal eat];

//实例化狗的对象
animal = [Dog new];
[animal eat];

13.实例变量访问修饰符

13.1.实例变量的作用域

@public

@private

@protected

注意: 默认情况下所有的实例变量都是protected

@package

@interface Person : NSObject
{
    @public
    int _age;
    
    @private
    double _height;
    
    @protected// 默认就是protected
    double _weight;
    
    @package// 相当于public
    NSString *_name;
    NSString *_tel;
    NSString *_email;
}
@end

14.私有变量和私有方法


@interface MyClass()
{
    NSString *Name;
}
@end

@implementation MyClass
//在.h文件中没有声明,只在.m文件中实现就是私有方法
- (void)method{
    
    // TODO
}
@end

15.@property概念

16. @property修饰符

17.id类型

17.1.静态类型和动态类型

17.2.为什么要有动态类型?

//定义NSObject * 类型
 NSObject* obj = [Cat new];
//需要强制类型转换
 Cat *c = (Cat*)obj
 [c eat];
/// Represents an instance of a class.
struct objc_object {
    Class isa  OBJC_ISA_AVAILABILITY;
};

/// A pointer to an instance of a class.
typedef struct objc_object *id;
 id obj = [C at new];
 [obj eat]; // 不用强制类型转换

 [obj test]; //可以调用私有方法

17.3.id数据类型与静态类型

    Person *p = [Person new];
    Student *stu = [Student new];

    BOOL res = [p isKindOfClass:[Person class]];
    NSLog(@"res = %i", res); // YES
    res = [stu isKindOfClass:[Person class]];
    NSLog(@"res = %i", res); // YES
    Person *p = [Person new];
    Student *stu = [Student new];

    BOOL res = [p isMemberOfClass:[Person class]];
    NSLog(@"res = %i", res); // YES
    res = [stu isMemberOfClass:[Person class]];
    NSLog(@"res = %i", res); // NO
    BOOL res = [Person isSubclassOfClass:[Student class]];
    NSLog(@"res = %i", res); // NO

    res = [Student isSubclassOfClass:[Person class]];
    NSLog(@"res = %i", res); // YES

18.new方法实现原理

This method is a combination of alloc and init. Like alloc, it initializes the isa instance variable of the new object so it points to the class data structure. It then invokes the init method to complete the initialization process.
The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0.
+ init方法是初始化方法(构造方法),用来对象成员变量进行初始化,默认实现是一个空方法。
An object isn’t ready to be used until it has been initialized. The init method defined in the NSObject class does no initialization; it simply returns self.
Person *p1 = [Person new];
Person *p = [[Person alloc] init];// 一般使用该方式创建对象

19.构造方法

19.1.默认构造方法

- (id)init {
    self = [super init];
    if (self) {
        // Initialize self.
    }
    return self;
}

//或者也可以这样
//- (id)init {
- (instancetype)init {
    if (self = [super init]) {
        // Initialize self.
    }
    return self;
}

19.2自定义构造方法

@interface Person : NSObject

@property int age;

@property NSString *name;

// 当想让对象一创建就拥有一些指定的值,就可以使用自定义构造方法
- (instancetype)initWithAge:(int)age;

- (instancetype)initWithName:(NSString *)name;

- (instancetype)initWithAge:(int)age andName:(NSString *)name;

@end
#import "Person.h"

@implementation Person

- (instancetype)init
{
    if (self = [super init]) {
        _age = 10;
    }
    return self;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"age = %i, name = %@", _age, _name];
}

- (instancetype)initWithAge:(int)age
{
    if (self = [super init]) {
        _age = age;
    }
    return self;
}

- (instancetype)initWithName:(NSString *)name
{
    if (self  =[super init]) {
        _name = name;
    }
    return self;
}

- (instancetype)initWithAge:(int)age andName:(NSString *)name
{
    if (self = [super init]) {
        _age = age;
        _name = name;
    }
    return self;
}

19.3.自定义类工厂方法

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property int age;
+ (instancetype)person;

+ (instancetype)personWithAge:(int)age;
@end
#import "Person.h"

@implementation Person

+ (instancetype)person
{
    return [[Person alloc] init];
}

+ (instancetype)personWithAge:(int)age
{
    Person *p = [[Person alloc] init];
    p.age = age;
    return p;
}

@end

20. instancetype与id

// init此时返回值是id
NSString *str = [[Person alloc] init];
// Person并没有length方法, 但是id是动态类型, 所以编译时不会报错
NSLog(@"length = %i", str.length);

----------------------------

// init此时返回值是instancetype
// 由于instancetype它会进行类型检查, 所以会报警告
NSString *str = [[Person alloc] init];
NSLog(@"length = %i", str.length);

----------------------------
instancetype *p = [[person alloc] init];
// 错误写法instancetype只能作为返回值

21.类的启动过程

21.1.+load方法

@implementation Person

+ (void)load
{
    NSLog(@"%s", __func__);
}
@end

@implementation Student : Person

+ (void)load
{
    NSLog(@"%s", __func__);
}
@end

输出结果:
+[Person load]
+[Student load]

21.2.+initialize

@implementation Person
+ (void)initialize
{
    NSLog(@"%s", __func__);
}
@end

@implementation Student : Person
+ (void)initialize
{
    NSLog(@"%s", __func__);
}
@end
int main(int argc, const char * argv[]) {
    Student *stu = [Student new];
    return 0;
}
输出结果:
+[Person initialize]
+[Student initialize]
比较项 +load +initialize
调用时机 被添加到 runtime 时 收到第一条消息前,可能永远不调用
调用顺序 父类->子类->分类 父类->子类
调用次数 1次 多次
是否需要显式调用父类实现
是否沿用父类的实现
分类中的实现 类和分类都执行 覆盖类中的方法,只执行分类的实现

22.SEL介绍

22.1.SEL类型

Dog *dog=[[Dog alloc] init];
[dog eat];

22.2.SEL使用

    BOOL flag;
    // [类 respondsToSelector]用于判断是否包含某个类方法
    flag = [Person respondsToSelector:@selector(objectFun)]; //NO
    flag = [Person respondsToSelector:@selector(classFun)]; //YES

    Person *obj = [[Person alloc] init];

    // [对象 respondsToSelector]用于判断是否包含某个对象方法
    flag = [obj respondsToSelector:@selector(objectFun)]; //YES
    flag = [obj respondsToSelector:@selector(classFun)]; //NO

    // [类名 instancesRespondToSelector]用于判断是否包含某个对象方法
    // instancesRespondToSelectorr只能写在类名后面, 等价于 [对象 respondsToSelector]
    flag = [Person instancesRespondToSelector:@selector(objectFun)]; //YES
    flag = [Person instancesRespondToSelector:@selector(classFun)]; //NO
    Person *p = [Person new];
    SEL s1 = @selector(objectFun);
    [p performSelector:s1];

    SEL s2 = @selector(objectFun:);
    [p performSelector:s2 withObject:@"seltest"];

    SEL s3 = @selector(objectFun:value2:);
    [p performSelector:s3 withObject:@"gzs" withObject:@"seltest"];

    SEL s4 = @selector(classFun);
    [Person performSelector:s4];

    SEL s5 = @selector(classFun:);
    [Person performSelector:s5 withObject:@"seltest"];

    SEL s6 = @selector(classFun:value2:);
    [Person performSelector:s6 withObject:@"seltest" withObject:@"seltest2"];
@implementation Person

- (void)makeObject:(id) obj performSelector:(SEL) selector
{
    [obj performSelector:selector];
}
@end

int main(int argc, const char * argv[]) {

    Person *p = [Person new];
    SEL s1 = @selector(eat);
    Dog *d = [Dog new];
    [p makeObject:d performSelector:s1];

    return 0;
}

22.3.OC方法查找顺序

23.@class使用

23.1.基本概念

#import "B.h"
@interface A : NSObject
{
    B *_b;
}
@end

#import “A.h"
@interface B : NSObject
{
    A *_a;
}
@end

@class B;
@interface A : NSObject
{
    B *_b;
}
@end

@class A;
@interface B : NSObject
{
    A *_a;
}
@end

23.2.@class和#import

24.注释和指令

24.1.#pragma mark指令的使用

24.2.其他指令

25.分类

25.1.什么是分类(Category)

25.2.Category的格式

@interface ClassName (CategoryName)
NewMethod; //在类别中添加方法
//不允许在类别中添加变量
@end
@implementation ClassName(CategoryName)

NewMethod
... ...
@end

25.3.分类的使用注意事项

@interface Person (gz)
{
//    错误写法
//    int _age;
}
- (void)eat;
@end
@interface Person (gz)
// 只会生成getter/setter方法的声明, 不会生成实现和私有成员变量
@property (nonatomic, assign) int age;
@end
@interface Person : NSObject
{
    int _no;
}
@end

@implementation Person (gz)
- (void)say
{
    NSLog(@"%s", __func__);
    // 可以访问原有类中得成员变量
    NSLog(@"no = %i", _no);
}
@end

@implementation Person

- (void)sleep
{
    NSLog(@"%s", __func__);
}
@end

@implementation Person (gz)
- (void)sleep
{
    NSLog(@"%s", __func__);
}
@end

int main(int argc, const char * argv[]) {
    Person *p = [[Person alloc] init];
    [p sleep];
    return 0;
}

输出结果:
-[Person(gz) sleep]

25.4.分类的编译的顺序

@implementation Person

- (void)sleep
{
    NSLog(@"%s", __func__);
}
@end

@implementation Person (gz)
- (void)sleep
{
    NSLog(@"%s", __func__);
}
@end

@implementation Person (zz)
- (void)sleep
{
    NSLog(@"%s", __func__);
}
@end

int main(int argc, const char * argv[]) {
    Person *p = [[Person alloc] init];
    [p sleep];
    return 0;
}

输出结果:
-[Person(zz) sleep]

25.5类扩展

@interface 类名 ()
@end

#import "Person.h"

@interface Person()

// 没在.h文件中声明,属于私有属性
@property (nonatomic, strong) NSArray *array;

// 没在.h文件中声明,属于私有方法
- (void)say;


@end

@implementation Person

- (void)say{
   // TODO
}

@end

26. Block

26.1.Block介绍

26.2.block的格式

返回值类型 (^block变量名)(形参列表) = ^(形参列表) {

};
void (^block名)() = ^{代码块;}

例如:
void (^myBlock)() = ^{ NSLog(@"block"); };
void (^block名称)(参数列表)
= ^ (参数列表) { // 代码实现; }

例如:
void (^myBlock)(int) = ^(int num){ NSLog(@"num = %i", num); };
返回类型 (^block名称)(参数列表)
= ^ (参数列表) { // 代码实现; }

例如:
int (^myBlock)(int, int) = ^(int num1, int num2){ return num1 + num2; };
block变量名(实参);
例如:
// 调用了block的最简单形式
myBlock();

// 调用了带有参数的block
myBlock(10);

// 调用了带有参数和返回值的block
myBlock(10, 20);

本文参考网络上资料结合自己的理解写出来的,个人理解能力有限,如果有错误的地方,欢迎批评指正,谢谢!祝大家玩的开心!

上一篇 下一篇

猜你喜欢

热点阅读