Objective-C方法的聲明實現(xiàn)及調(diào)用方法
1.無參數(shù)的方法
1)聲明
a.位置:在@interface括弧的外面
b.語法:
- (返回值類型)方法名稱;
@interface Person : NSObject -(void) run; @end
2)實現(xiàn)
a.位置:在@implementation中實現(xiàn)
b.語法:加大括弧將方法實現(xiàn)的代碼寫在大括孤之中
@implementation Person; -(void)run{ NSLog(@"我在跑步"); } @end
3)調(diào)用
a.方法是無法直接調(diào)用的,因為類是不能直接使用的,必須要先創(chuàng)建對象
b.語法:
[對象名 方法名];
int main(int argc, const char * argv[]) { Person *p = [Person new]; [p run]; }
2.單個參數(shù)的方法
1)聲明
a.位置:在@interface括弧的外面
b.語法:
-(返回值類型)方法名稱:(參數(shù)類型)形參名稱;
@interface Person : NSObject -(void)eat:(NSString *)foodName; @end
2)實現(xiàn)
a.位置:在@implementation中實現(xiàn)
b.語法:加大括弧將方法實現(xiàn)的代碼寫在大括孤之中
@implementation Person; -(void)eat:(NSString *)foodName{ NSLog(@"%@好美味!",foodName); } @end
3)調(diào)用
a.方法是無法直接調(diào)用的,因為類是不能直接使用的,必須要先創(chuàng)建對象
b.語法:
[對象名 方法名:實參];
int main(int argc, const char * argv[]) { Person *p = [Person new]; [p eat:@"烤魚"]; }
3.多個參數(shù)的方法
1)聲明
a.位置:在@interface括弧的外面
b.語法:
-(返回值類型)方法名稱:(參數(shù)類型)形參名稱 :(參數(shù)類型)形參名稱;
@interface Person : NSObject -(int)sum:(int)num1 :(int)num2; @end
2)實現(xiàn)
a.位置:在@implementation中實現(xiàn)
b.語法:加大括弧將方法實現(xiàn)的代碼寫在大括孤之中
@implementation Person; -(int)sum:(int)num1 :(int)num2{ int num = num1+num2; return num; } @end
3)調(diào)用
a.方法是無法直接調(diào)用的,因為類是不能直接使用的,必須要先創(chuàng)建對象
b.語法:
[對象名 方法名:實參:實參];
int main(int argc, const char * argv[]) { Person *p = [Person new]; NSLog(@"sum=%d",[p sum:1 :1]); }
運行結(jié)果
補充:
Objective-C中的“description“方法
在Objective-C中,每個對象都繼承自NSObject類,在NSObject類中定義了一個名為`description`的方法。該方法用于返回一個字符串,描述對象的內(nèi)容。默認(rèn)情況下,`description`方法返回的字符串是該對象的類名和其在內(nèi)存中的地址。
下面是一個重寫`description`方法的示例代碼:
@interface MyClass : NSObject @property (nonatomic, strong) NSString *name; @property (nonatomic) NSInteger age; @end @implementation MyClass - (NSString *)description { return [NSString stringWithFormat:@"MyClass: Name=%@, Age=%ld", self.name, (long)self.age]; } @end
定義了一個叫做`MyClass`的類,它包含了`name`和`age`兩個屬性
重寫了`description`方法,使用`NSString`的`stringWithFormat:`方法
將`name`和`age`的值拼接到一個描述字符串中,并返回
MyClass *myObject = [[MyClass alloc] init]; myObject.name = @"John"; myObject.age = 25; NSLog(@"%@", myObject); // 輸出: MyClass: Name=John, Age=25
通過重寫`description`方法,你可以為自定義的類提供更有意義的描述信息,方便在日志輸出和調(diào)試過程中使用。
需要注意的是,為了在控制臺上輸出一個對象的`description`內(nèi)容,你可以使用`NSLog`方法,并將對象作為參數(shù)傳遞給`%@`占位符
到此這篇關(guān)于Objective-C方法的聲明實現(xiàn)及調(diào)用的文章就介紹到這了,更多相關(guān)Objective-C方法的聲明內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
實例講解iOS應(yīng)用的設(shè)計模式開發(fā)中的Visitor訪問者模式
這篇文章主要介紹了iOS應(yīng)用的設(shè)計模式開發(fā)中的Visitor訪問者模式的實例,示例代碼為傳統(tǒng)的Objective-C,需要的朋友可以參考下2016-03-03IOS 開發(fā)之 NSMutableArray與NSArray 的區(qū)別
這篇文章主要介紹了IOS 開發(fā)之 NSMutableArray與NSArray 的區(qū)別的相關(guān)資料,希望通過本文能掌握這部分內(nèi)容,需要的朋友可以參考下2017-09-09