m移动端基础知识浅谈

浅谈Objective-C的方法与函数

2017-11-27  本文已影响0人  JTR354
方法 函数
-(void)test{}; void test(){};
方法的表示:实例方法-,类方法+ -
类型要用()括起来 -
声明必须@interface-@end之间,实现@implementation-@end之间 可以写在文件中的任意位置
只能有对象来调用 -
可以直接访问成员变量 不可以直接访问成员变量
方法可以重载 函数不可以重载

举例说明:

// classXX.h文件
@interface Founction : NSObject
-(void)hello;
-(void)hello:(NSString*)str;
@end
//classA.m文件
@implementation Founction
-(void)hello{
    NSLog(@"hello");
    console(@"javaScript");
}
//方法可以重载
-(void)hello:(NSString*)str{
    NSLog(@"%@",str);
    [self print];
}
-(void)print{
    NSLog(@"print");
}
//函数不可以重载
void console(){
    NSLog(@"13123");
}
//void console(NSString*name){
//    NSLog(@"%@",name);
//}
@end
//入口文件等等
#import <Foundation/Foundation.h>
#import "Parent.h"
#import "Founction.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Founction *fn =  [[Founction alloc]init];
        [fn hello];
        [fn hello:@"world"];
        
    }
    return 0;
}

Objective-C方法命名的问题

函数的方法命名和主流编程语言类似

void hello(int a,NSString* str){
    NSLog(@"hello");
}
void print(){
    NSLog(@"hello world");
}
void printStr(NSString* str,int num,double d,float f,char c,BOOL b,id obj){
    NSLog(@"%@,%d,%f,%f,%c,%d,%@",str,num,d,f,c,b,obj);
}

方法的命名比较诡异

(返回值类型)函数名:(参数1数据类型)参数1的数值的名字 参数2的名字: (参数2数据类型) 参数2值的名字 …. ;

-(void) setKids: (NSString *)myOldestKidName secondKid: (NSString *) mySecondOldestKidName thirdKid: (NSString *) myThirdOldestKidName;
-(void) setKids: (NSString *)myOldestKidName secondKid: (NSString *) mySecondOldestKidName thirdKid: (NSString *) myThirdOldestKidName
{  
大儿子 = myOldestKidName; 二儿子 = mySecondOldestKidName; 三儿子 = myThirdOldestKidName;
}
Kids *myKids = [[Kids alloc] init];

[myKids setKids: @”张大力” secondKid: @”张二力” thirdKid: @”张小力”];

关于@selector

SEL类型代表着方法的签名,在类对象的方法列表中存储着该签名与方法代码的对应关系

//helloworld.m文件

#import "helloWorld.h"

@implementation helloWorld
-(void)fn{
    NSLog(@"hello world");
}
-(void)fn:(NSString *)str{
    NSLog(@"%@",str);
}
-(void)fn:(id)obj two:(NSString *)str three:(BOOL)flag four:(int)num five:(float)money six:(double)bigM{
    NSLog(@"id=%@,two=%@,three=%d,four=%d,five=%f,six=%f",obj,str,flag,num,money,bigM);
}
-(void)fn:(id)obj obj2:(id)o2 obj3:(id)o3{
    NSLog(@"1=%@,2=%@,3=%@",obj,o2,o3);
}
-(void)fn:(id)obj obj2:(id)o2{
    NSLog(@"1=%@,2=%@,3=%%",obj,o2);
}
@end

//
        [hw performSelector:@selector(fn) withObject:nil];
        [hw performSelector:@selector(fn:) withObject:@"adsasd123"];
        [hw performSelector:@selector(fn:obj2:) withObject:@"1" withObject:@"2" ];
/*
2017-12-07 13:44:17.154625+0800 function_func[37303:5805459] hello world
2017-12-07 13:44:17.154856+0800 function_func[37303:5805459] adsasd123
2017-12-07 13:44:17.154872+0800 function_func[37303:5805459] 1=1,2=2,3=%
Program ended with exit code: 0
*/

参考:

上一篇 下一篇

猜你喜欢

热点阅读