微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

Person.h

#ifndef Person_h
#define Person_h

#import <Foundation/Foundation.h>
@interface Person : NSObject
{
    Nsstring* _name;
    int _age;
}
-(void)setName:(Nsstring *)name addAge:(int)age;
-(void)say:(Nsstring *)content;
-(Nsstring *)info;
+(void)foo;
@end
#endif /* Person_h */

Person.m

#import "Person.h"

@implementation Person
{
    int _testAdd;
}
-(void)setName:(Nsstring *)name addAge:(int)age {
    _name = name;
    _age = age;
}
-(void)say:(Nsstring *)content
{
    NSLog(@"content is %@",content);
}
-(Nsstring *)info
{
    [self test];
    return [Nsstring stringWithFormat:@"the persion is %@,and age is %d",_name,_age];
}
-(void)test
{
    NSLog(@"this is test method");
}

+(void)foo
{
    NSLog(@"this is foo method");
}
@end

main.m

#import "Person.h"

int main(int argc,char * argv[]) {
    @autoreleasepool {
        Person *person = [[Person alloc] init];
        [person setName:@"chenyu" addAge:26];
        Nsstring *info = [person info];
        NSLog(@"%@",info);
        [person say:@"chenyu"];
        [Person foo];
        //id类型可以代表所有对象的类型,id类型执行方法会动态绑定
        //id p不是id *p;
        id p = [[Person alloc] init];
        [p setName:@"chenyu" addAge:26];
        Nsstring *in = [p info];
        NSLog(@"%@",in);
        [p say:@"chenyu"];
    }
}

 

 

 


2、运行结果

this is test method
the persion is chenyu,and age is 26
content is chenyu
this is foo method
this is test method
the persion is chenyu,and age is 26
content is chenyu

 

 

 

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐