协议 |
@required //必须实现的方法
-(void)study;
@optional //可实现可不实现的方法
-(void)work;
@implementationStudeny
-(void)study{
NSLog(@"%s",__func__);
}
//-(void)work{
// NSLog(@"%s",__func__);
#import"Studeny.h"
@autoreleasepool{
Studeny*stu=[[Studenyalloc]init];
// [stu study];
//判断协议是否有该方法
if([sturespondsToSelector:@selector(study)]){
[stustudy];
// [stu work];
}else{
NSLog(@"找不到好工作");
}
}else{
NSLog(@"没有参加培训");
}
if([stuconformsToProtocol:@protocol(lamcoProtocol)]){
if([sturespondsToSelector:@selector(giveMoney)]) {
NSLog(@"每月还钱");
}else{
NSLog(@"成为黑户");
}
}else{
NSLog(@"不关事");
}
}
return0;
延展 |
#import"MyClass.h"
@interfaceMyClass()
-(void)add;
@interfaceMyClass :NSObject
-(void)select;
@implementationMyClass
-(void)select{
NSLog(@"%s",__func__);
}
-(void)add{
NSLog(@"%s",__func__);
}
intmain(intargc,constchar* argv[]) {
@autoreleasepool{
MyClass*class=[[MyClassalloc]init];
[classselect];
[classadd];
}
return0;
分类(类目) |
#import<Foundation/Foundation.h>
#import"NSString+CategoryNSString.h"
intmain(intargc,constchar* argv[]) {
@autoreleasepool{
NSString*str=@"abc";
NSLog(@"%@", [str Reverser]);
NSLog(@"%d",[str leng].intValue);
}
return0;
#import<Foundation/Foundation.h>
@interfaceNSString (CategoryNSString)
-(NSString*)Reverser;
-(NSNumber*)leng;
#import"NSString+CategoryNSString.h"
@implementationNSString (CategoryNSString)
/**
* 字符串反转函数
*
* @param string传入的字符串
*
* @return逆序后的字符串
*/
-(NSString*)Reverser{
NSMutableString*str=[NSMutableStringstring];
for(unsignedlongi=(self.length); i>0; i--) {
[strappendFormat:@"%c",[selfcharacterAtIndex:i-1]];
}
returnstr;
}
/**
* 把字符串长度int类型变成NSNumber类型
*
* @param string出入的字符串
*
* @return NSNumber,字符串的长度
*/
-(NSNumber*)leng{
NSNumber*num=[[NSNumberalloc]initWithUnsignedLong:self.length];
returnnum;
}
![](https://images2015.cnblogs.com/blog/818241/201603/818241-20160302171158126-973086370.png)
@interfaceMyClass :NSObject
-(void)Select;
@end
@interfaceMyClass (CategoryUpdate)
-(void)update;
@end
@interfaceMyClass (CategoryAdd)
-(void)add;
@end
@interfaceMyClass (CategoryDeleta)
-(void)delect;
-(void)Select{
NSLog(@"%s",__func__);
}
@implementationMyClass (CategoryAdd)
-(void)add{
NSLog(@"%s",__func__);
}
@implementationMyClass (CategoryUpdate)
-(void)update{
NSLog(@"修改");
}
@implementationMyClass (CategoryDeleta)
-(void)delect{
NSLog(@"删除");
}