IOS之学习笔记四(类的实现和对象和id)

举报
chenyu 发表于 2021/07/27 01:05:36 2021/07/27
【摘要】 1、简单构建类和对象和id使用的测试代码如下 Person.h #ifndef Person_h#define Person_h #import <Foundation/Foundation.h>@interface Person : NSObject{ NSString* _name; int _age;}-(void)setName:(NSString *...

1、简单构建类和对象和id使用的测试代码如下

Person.h


  
  1. #ifndef Person_h
  2. #define Person_h
  3. #import <Foundation/Foundation.h>
  4. @interface Person : NSObject
  5. {
  6. NSString* _name;
  7. int _age;
  8. }
  9. -(void)setName:(NSString *)name addAge:(int)age;
  10. -(void)say:(NSString *)content;
  11. -(NSString *)info;
  12. +(void)foo;
  13. @end
  14. #endif /* Person_h */

Person.m


  
  1. #import "Person.h"
  2. @implementation Person
  3. {
  4. int _testAdd;
  5. }
  6. -(void)setName:(NSString *)name addAge:(int)age {
  7. _name = name;
  8. _age = age;
  9. }
  10. -(void)say:(NSString *)content
  11. {
  12. NSLog(@"content is %@", content);
  13. }
  14. -(NSString *)info
  15. {
  16. [self test];
  17. return [NSString stringWithFormat:@"the persion is %@, and age is %d", _name, _age];
  18. }
  19. -(void)test
  20. {
  21. NSLog(@"this is test method");
  22. }
  23. +(void)foo
  24. {
  25. NSLog(@"this is foo method");
  26. }
  27. @end

main.m


  
  1. #import "Person.h"
  2. int main(int argc, char * argv[]) {
  3. @autoreleasepool {
  4. Person *person = [[Person alloc] init];
  5. [person setName:@"chenyu" addAge:26];
  6. NSString *info = [person info];
  7. NSLog(@"%@", info);
  8. [person say:@"chenyu"];
  9. [Person foo];
  10. //id类型可以代表所有对象的类型,id类型执行方法会动态绑定
  11. //id p不是id *p;
  12. id p = [[Person alloc] init];
  13. [p setName:@"chenyu" addAge:26];
  14. NSString *in = [p info];
  15. NSLog(@"%@", in);
  16. [p say:@"chenyu"];
  17. }
  18. }

 

 

 


2、运行结果


  
  1. this is test method
  2. the persion is chenyu, and age is 26
  3. content is chenyu
  4. this is foo method
  5. this is test method
  6. the persion is chenyu, and age is 26
  7. content is chenyu

 

 

 

 

 

 

文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/80933896

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。