iOS学习——第五天

来源:互联网 发布:python twisted过时 编辑:程序博客网 时间:2024/05/18 00:49

1.@protocol:协议(相当于JAVA中的接口),可多继承(<protocol1,protocol2,…..>)

建立方式:


eg;在parent类中继承protocol


//MyProtocol.h

#import<Foundation/Foundation.h>


@protocol MyProtocol <NSObject>

-(void)fun1;

@end


//Parent.h

#import<Foundation/Foundation.h>

#import"MyProtocol.h"


@interface Parent :NSObject <MyProtocol>


@property (strong,nonatomic)NSMutableString *str;


-(void)fun1;//必须实现接口中的方法


@end


2.category

扩展现有类的方法,可利用被扩展类的对象调用扩展的方法

category只能添加方法,不能添加变量


建立方式:


catefory on Parent

建立好之后:



//Parent+MyCategory.h

#import"Parent.h"


@interface Parent (MyCategory)

-(void) test2;

@end


//Parent+MyCategory.m

#import"Parent+MyCategory.h"


@implementation Parent (MyCategory)

-(void) test2

{

   NSLog(@"Category");

}

@end


//AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

   // Override point for customization after application launch.

    Parent *p=[[Parent alloc] init];

    [ptest2];//可调用扩展的方法

   returnYES;

    

}


3.extension

//Parent.h

#import<Foundation/Foundation.h>

#import"MyProtocol.h"


@interface Parent :NSObject <MyProtocol>


@property (strong,nonatomic,readonly)NSMutableString *str;//成员变量的属性定义为readonly


-(void)fun1;//必须实现接口中的方法


@end


//Parent.m

#import"Parent.h"


@interfaceParent()

@property (strong,nonatomic,readwrite)NSMutableString *str;//在自己的成员变量的属性改为readwrite,这样就可以对外暴露readonly,但内部可修改

@end


@implementation Parent

-(void) fun1

{

   self.str=[[NSMutableStringalloc]initWithString:@"test"];//可修改

}

@end

方法不可以通过此方法保护,只要实现了方法就一定可以被调用


原创粉丝点击