objective-c面向对象

(一)对象

(1) l类和接口的名称与其他语言的区别

//                             类                 接口

//objective-c       @interface      @protocal

//swift                 class              protocal

//java                  class              interface

(2)类的写法

objective-c中的类分成两部分:定义和实现。一般分别写在.h文件和.m文件中(cocoa class),也可以写在一起。例子如下:

@interface ClassName : SuperClass<protocal1, protocal2>

{

  成员变量

  //int variable;

}

@property NSString* myString;

+(void)staticMethod;

-(void)instanceMethod;

-(void)instanceMethod:(NSString*)para1 AndTheOther:(NSString*)para2;

-(instancetype)init;

@end

@implementation ClassName

+(void)staticMethod{

  NSLog(@"Hello World!");

}

-(void)instanceMethod{

  NSLog(@"Hello World");

}

-(void)instanceMethod:(NSString*)para1 AndTheOther:(NSString*)para2{

  NSLog(@"Hello World to %@ and %@", para1, para2);

}

//模版, 重写基类的init函数,没有override关键字

-(instancetype)init{

  self = [super init];

  if(self){

    statements;

  }

  return self;

}

@end

注:类只能继承自一个基类,但是可以实现多个协议

(3)类的实例化

ClassName* pointer = [ [ClassName alloc] init];

(4)协议的写法

xcode中创建协议选择Objective-C File,文件类型选择protocal。(最后是一个.h文件)

@protocal ProtocalName<SuperProtocal>

@required

//必须实现的方法

@optional

//可选方法

@end

(5) Getter and Setter

Setter使用时有两种写法:

  • m.name = name;
  • [m setName:name];

Getter使用时有两种写法:

  • NSString s = m.name;
  • NSString s = [m name];

注:getName一般指传入一个指针然后返回值,所以这里name不要改成getName,容易引起歧义

注:定义一个属性后,setName和name自动生成,还会生成一个成员变量_name。

注:默认生成的setName和name可以改名,方法时@property(nonatomic, getter=getName)NSString name;

(6) Category

xcode中创建协议选择Objective-C File,文件类型选择category, 同时选择要扩展的类。(最后是一个.h文件和一个.m文件)

@interface NSString (EndWith)

-(BOOL)endWith:(NSString*)end;

@end

@implementation NSString(EndWith)

-(BOOL)endWith:(NSString*)end{

  NSString* selfEnd = [self subStringFromIndex:[self length]-[end length]];

  return [selfEnd isEqualToString:end];

}

@end

使用的时候,只要引入头文件,所有的NSString便具有了EndWith这个函数。

注:Category用在没有源代码的时候扩展类的功能

(7)Extension

xcode中创建协议选择Objective-C File,文件类型选择extension, 同时选择对象类。(最后是一个.h文件)

在生成的头文件中定义方法和属性,在原类的实现中实现。如果外界不引入这个头文件,便无法使用这些方法和属性,因此可以通过这个方法对外界隐藏某些方法和属性。

@interface ClassName()

@end

注:多了一个括号

注:如果直接把这些代码写到实现文件的上面可以更好的隐藏

注:如果在原头文件中定义了一个只读属性,在extension的头文件中定义了一个读写属性,那么外界就是只读的,内部就是可读写的。

(8)Block

定义:

void(^BlockName)()=^{

  statements;

}

使用:

BlockName();

赋值:

void(^h)()=BlockName;

带参数的:

int(^max)(int,int) = ^(int a, int b){

  return a>b?a:b;

}

max(2, 3);

注:block用在函数指针或者匿名函数的场合

原文地址:https://www.cnblogs.com/jacky1982/p/7518368.html