oc 상속

3876 단어 물려받다oc
클래스의 계승은 oop의 기본 원칙입니다. 다음에oc의 클래스와 계승을 분석해 보겠습니다.
계승을 실현하는데 자류가 생겼다.파일 오류mission@end프로그램이 컴파일되지 않았는데, 마지막에 발견한 것은.h에 @end 하나 없음
 
상위 TestExtends.h 파일
@interface TestExtends: NSObject{
    
NSString* name;
    
}
@property NSString *name; //  set get  

//@property name;


-(void)setName:(NSString*)newName;//    

-(id)initWithC:(NSString*)newName;//      


@end

#endif /* TestExtends_h */

 
TestExtends.m 파일
#import <Foundation/Foundation.h>
#import "TestExtends.h"

@implementation TestExtends

@synthesize name;

-(void)setName:(NSString*)newName{

    NSLog(@"     setName  ");

}

-(id)initWithC:(NSString *)newName{
    if (self==[super init]) {
        name=newName;//
        NSLog(@"          。。。。");
    }

    return self;
}

@end

 
mian 파일
 TestExtends* te=[[TestExtends alloc] init];
        [te setName:@"Object-c"];
        NSLog(@"     "); 

 
실행 결과:
2015-11-04 22:35:10.327 test_01[1287:67105] 상위 클래스의 setName 메서드를 호출합니다.
2015-11-04 22:35:10.328 test_01[1287:67105] 간단한 실현
 
(lldb) 
 
분석하다.
객체 작성
 
   TestExtends* te=[[TestExtends alloc] init];
setName 메서드 호출하기
        [te setName:@"Object-c"];
 
NSLog(@ "간단한 실행")
 
 
하위 클래스 정의 Person 클래스 상속 TestExtends 클래스
 
TestExtends.h 파일
#import "TestExtends.h"

@interface Person :TestExtends

@property NSString* address;//    

-(void)setAddress:(NSString*)newAssress;//    

-(id)initWithChild:(NSString*)newAssress;//         

@end


#endif /* Person_h */

 
TestExtends.m 파일
 
#import "Person.h"

@implementation Person

@synthesize address;


-(void)setAddress:(NSString *)newAssress{

    [super setName:newAssress];
    
    NSLog(@"      %@",newAssress);
}

-(id)initWithChild:(NSString *)newAssress{

    
    if (self==[super initWithC:newAssress]) {

        address=newAssress;
        NSLog(@"           。。。");
    }
    return self;
}


@end

 
main 파일
    Person* tec=[[Person alloc]initWithChild:@"Android"];
        [tec setAddress:@"China"];
        

실행 결과:
2015-11-04 22:40:42.288 test_01[1306:70521]           。。。。
2015-11-04 22:40:42.289 test_01[1306:70521]            。。。
2015-11-04 22:40:42.289 test_01[1306:70521]      setName  
2015-11-04 22:40:42.289 test_01[1306:70521]       China
(lldb) 

분석:
  1,  Person* tec=[[Person alloc]initWithChild:@"Android"];창설 대상이 먼저 부류를 호출하는 방법: 원인은 다음과 같다.
-(id)initWithChild:(NSString *)newAssress{

    
    if (self==[super initWithC:newAssress]) {//         

        address=newAssress;
        NSLog(@"           。。。");
    }
    return self;
}

 
  
2, [tec setAddress:@"China"];메서드에는 [supersetName:new Assress]가 있습니다.부모 클래스를 호출하는 방법
 
 
 
mian 파일의 Person* tec=[[Personalloc] initWithChild:@"Android"];
        [tec setAddress:@"China"];
 
TestExtends* te=[[Person alloc] init]로 변경;
        [te setName:@"nihao"];
 
실행 결과:
2015-11-04 23:20:16.150 test_01[1479:87156] 상위 클래스의 setName 메서드를 호출합니다.

좋은 웹페이지 즐겨찾기