1.无参数的方法
1)声明
a.位置:在@interface括弧的外面
b.语法:
- (返回值类型)方法名称;
@interface person : nsobject -(void) run; @end
2)实现
a.位置:在@implementation中实现
b.语法:加大括弧将方法实现的代码写在大括孤之中
@implementation person; -(void)run{ nslog(@"我在跑步"); } @end
3)调用
a.方法是无法直接调用的,因为类是不能直接使用的,必须要先创建对象
b.语法:
[对象名 方法名];
int main(int argc, const char * argv[]) { person *p = [person new]; [p run]; }
2.单个参数的方法
1)声明
a.位置:在@interface括弧的外面
b.语法:
-(返回值类型)方法名称:(参数类型)形参名称;
@interface person : nsobject -(void)eat:(nsstring *)foodname; @end
2)实现
a.位置:在@implementation中实现
b.语法:加大括弧将方法实现的代码写在大括孤之中
@implementation person; -(void)eat:(nsstring *)foodname{ nslog(@"%@好美味!",foodname); } @end
3)调用
a.方法是无法直接调用的,因为类是不能直接使用的,必须要先创建对象
b.语法:
[对象名 方法名:实参];
int main(int argc, const char * argv[]) { person *p = [person new]; [p eat:@"烤鱼"]; }
3.多个参数的方法
1)声明
a.位置:在@interface括弧的外面
b.语法:
-(返回值类型)方法名称:(参数类型)形参名称 :(参数类型)形参名称;
@interface person : nsobject -(int)sum:(int)num1 :(int)num2; @end
2)实现
a.位置:在@implementation中实现
b.语法:加大括弧将方法实现的代码写在大括孤之中
@implementation person; -(int)sum:(int)num1 :(int)num2{ int num = num1+num2; return num; } @end
3)调用
a.方法是无法直接调用的,因为类是不能直接使用的,必须要先创建对象
b.语法:
[对象名 方法名:实参:实参];
int main(int argc, const char * argv[]) { person *p = [person new]; nslog(@"sum=%d",[p sum:1 :1]); }
运行结果
补充:
objective-c中的“description“方法
在objective-c中,每个对象都继承自nsobject类,在nsobject类中定义了一个名为`description`的方法。该方法用于返回一个字符串,描述对象的内容。默认情况下,`description`方法返回的字符串是该对象的类名和其在内存中的地址。
下面是一个重写`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`方法,你可以为自定义的类提供更有意义的描述信息,方便在日志输出和调试过程中使用。
需要注意的是,为了在控制台上输出一个对象的`description`内容,你可以使用`nslog`方法,并将对象作为参数传递给`%@`占位符
到此这篇关于objective-c方法的声明实现及调用的文章就介绍到这了,更多相关objective-c方法的声明内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论