IOS之學(xué)習(xí)筆記四(類的實(shí)現(xiàn)和對(duì)象和id)

1、簡(jiǎn)單構(gòu)建類和對(duì)象和id使用的測(cè)試代碼如下

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類型可以代表所有對(duì)象的類型,id類型執(zhí)行方法會(huì)動(dòng)態(tài)綁定
            //id p不是id *p;
            id p = [[Person alloc] init];
            [p setName:@"chenyu" addAge:26];
            NSString *in = [p info];
            NSLog(@"%@", in);
            [p say:@"chenyu"];
        }
    }

 

2、運(yùn)行結(jié)果

    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

 



 

 
作者:chen.yu
深信服三年半工作經(jīng)驗(yàn),目前就職游戲廠商,希望能和大家交流和學(xué)習(xí),
微信公眾號(hào):編程入門(mén)到禿頭 或掃描下面二維碼
零基礎(chǔ)入門(mén)進(jìn)階人工智能(鏈接)