development

.h 및 .m 파일의 @interface 정의 차이점

big-blog 2020. 10. 8. 08:13
반응형

.h 및 .m 파일의 @interface 정의 차이점


일반적으로 우리는

@interface interface_name : parent_class <delegates>
{
......
}
@end 

.h 파일과 .m 파일의 메소드는 .h 파일에 선언 된 변수의 속성을 합성합니다.

그러나 일부 코드에서는이 @interface ..... @ end 메서드가 .m 파일에도 유지됩니다. 무슨 뜻이에요? 그들 사이의 차이점은 무엇입니까?

또한 .m 파일에 정의 된 인터페이스 파일의 getter 및 setter에 대한 몇 가지 단어를 제공하십시오.

미리 감사드립니다


@interfaceprivate 메서드를 포함하는 카테고리를 정의 하는 추가를 넣는 것이 일반적입니다 .

Person.h :

@interface Person
{
    NSString *_name;
}

@property(readwrite, copy) NSString *name;
-(NSString*)makeSmallTalkWith:(Person*)person;
@end

Person.m :

@interface Person () //Not specifying a name for the category makes compiler checks that these methods are implemented.

-(void)startThinkOfWhatToHaveForDinner;
@end


@implementation Person

@synthesize name = _name;

-(NSString*)makeSmallTalkWith:(Person*)person
{
    [self startThinkOfWhatToHaveForDinner];
    return @"How's your day?";
}


-(void)startThinkOfWhatToHaveForDinner
{

}

@end

'비공개 카테고리'(이름없는 카테고리의 적절한 이름은 '비공개 카테고리'가 아니라 '클래스 확장'임) .m은 컴파일러가 메소드가 정의되었다는 경고를하지 않도록합니다. 그러나 @interface.m 파일의는 범주 이기 때문에 ivar를 정의 할 수 없습니다.

업데이트 6th Aug '12 :이 답변이 작성된 이후 Objective-C가 발전했습니다.

  • ivars 클래스 확장에서 선언 될 수 있습니다 (항상 가능-대답이 잘못됨)
  • @synthesize 필요하지 않습니다
  • ivars이제 맨 위에 중괄호로 선언 할 수 있습니다 @implementation.

그건,

@implementation { 
     id _ivarInImplmentation;
}
//methods
@end

개념은 .h를 클래스의 공용 인터페이스로 제한 한 다음이 클래스 확장에 개인 구현 세부 정보를 입력하면 프로젝트를 훨씬 더 깔끔하게 만들 수 있다는 것입니다.

when you declare variable methods or properties in ABC.h file , It means these variables properties and methods can be access outside the class

@interface Jain:NSObject
{
    NSString *_name;
}

@property(readwrite, copy) NSString *name;
-(NSString*)makeSmallTalkWith:(Person*)jain;
@end

@Interface allows you to declare private ivars, properties and methods. So anything you declare here cannot be accessed from outside this class. In general, you want to declare all ivars, properties and methods by default as private

Simply say when you declare variable methods or properties in ABC.m file , It means these variables properties and methods can not be access outside the class

@interface Jain()
    {
        NSString *_name;
    }

    @property(readwrite, copy) NSString *name;
    -(NSString*)makeSmallTalkWith:(Person*)jain;
    @end

you can even create other classes in .m file, for instance other small classes which inherit from the class declared in .h file but having some slight different behaviour. You could use this in a factory pattern

참고URL : https://stackoverflow.com/questions/3967187/difference-between-interface-definition-in-h-and-m-file

반응형