class extension in objective-c

前端 未结 6 1376
花落未央
花落未央 2021-01-07 01:48

I am learning object-c by reading a book. When I read the chapter about class extension, the book gives the following example code:

// A class extension
@int         


        
6条回答
  •  北荒
    北荒 (楼主)
    2021-01-07 02:18

    As per the Apple Docs 1. a class extension can add its own properties and instance variables to a class 2. Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation of the class itself.

    so if you declare the property in class extension it will be visible only to the implementation file. like

    in BNREmployee.m

    @interface BNREmployee ()
    
    @property (nonatomic) unsigned int officeAlarmCode;
    
    @end
    
    @implementation BNREmployee
    
    - (void) someMethod {
        //officeAlarmCode will be available inside implementation block to use
         _officeAlarmCode = 10;
    }
    @end
    

    If you want to use officeAlarmCode in other classes, let's say OtherEmployee class then you need to create officeAlarmCode property in BNREmployee.h file with readOnly or readWrite access. Then you can use it like

    BNREmployee.h
    
    @property (nonatomic, readOnly) unsigned int officeAlarmCode; //readOnly you can just read not write 
    

    in OtherEmployee.m

    import "BNREmployee.h"
    @interface OtherEmployee ()
    
    @property (nonatomic) unsigned int otherAlarmCode;
    
    @end
    
    @implementation OtherEmployee
    

    you can create instance of BNREmployee and can assign officeAlarmCode value to otherAlarmCode property like below

    BNREmployee *bnrEmployee = [BNREmployee alloc] init];
    _otherAlarmCode = bnrEmployee.officeAlarmCode;
    

提交回复
热议问题