- 方法唯對象所有
- 函數(shù)是不依賴于對象存在的
方法 | 函數(shù) |
---|---|
-(void)test{}; | void test(){}; |
方法的表示:實例方法-躺涝,類方法+ | - |
類型要用()括起來 | - |
聲明必須@interface-@end之間代虾,實現(xiàn)@implementation-@end之間 | 可以寫在文件中的任意位置 |
只能有對象來調用 | - |
可以直接訪問成員變量 | 不可以直接訪問成員變量 |
方法可以重載 | 函數(shù)不可以重載 |
舉例說明:
- 聲明
// classXX.h文件
@interface Founction : NSObject
-(void)hello;
-(void)hello:(NSString*)str;
@end
- 實現(xiàn)
//classA.m文件
@implementation Founction
-(void)hello{
NSLog(@"hello");
console(@"javaScript");
}
//方法可以重載
-(void)hello:(NSString*)str{
NSLog(@"%@",str);
[self print];
}
-(void)print{
NSLog(@"print");
}
//函數(shù)不可以重載
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方法命名的問題
函數(shù)的方法命名和主流編程語言類似
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);
}
方法的命名比較詭異
(返回值類型)函數(shù)名:(參數(shù)1數(shù)據(jù)類型)參數(shù)1的數(shù)值的名字 參數(shù)2的名字: (參數(shù)2數(shù)據(jù)類型) 參數(shù)2值的名字 …. ;
- 聲明
-(void) setKids: (NSString *)myOldestKidName secondKid: (NSString *) mySecondOldestKidName thirdKid: (NSString *) myThirdOldestKidName;
- 實現(xiàn)
-(void) setKids: (NSString *)myOldestKidName secondKid: (NSString *) mySecondOldestKidName thirdKid: (NSString *) myThirdOldestKidName
{
大兒子 = myOldestKidName; 二兒子 = mySecondOldestKidName; 三兒子 = myThirdOldestKidName;
}
- 調用
Kids *myKids = [[Kids alloc] init];
[myKids setKids: @”張大力” secondKid: @”張二力” thirdKid: @”張小力”];
關于@selector
SEL類型代表著方法的簽名谭羔,在類對象的方法列表中存儲著該簽名與方法代碼的對應關系
- 每個類的方法列表都存儲在類對象中
- 每個方法有一個與之對應的SEL類型的對象
- 根據(jù)一個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
*/