Objective-C的Public, Protected, Private变量和方法的使用
.h文
#import <Foundation/Foundation.h> @interface Grammar : NSObject { /* 变量缺省的作用域是Protected */ NSString* protectedVariable1; @public NSString* publicVariable1; @protected NSString* protectedVariable2; @private NSString* privateVariable; } /* 定义静态变量,所有的对象共享它 */ NSString* staticVariable; @property (nonatomic, retain) NSString* publicVariable2; + (void)staticMethod; - (void)publicMethod; @end
.m文件
#import "Grammar.h" //私有方法以category方式实现 #pragma mark - #pragma mark Grammar(private) @interface Grammar(private) - (void)privateMethod; @end #pragma mark - #pragma mark Grammar
@implementation Grammar
{
/* private权限实例变量定义于此 */
}
@synthesize publicVariable2; #pragma mark - #pragma mark Public Method + (void)staticMethod { } - (void)publicMethod { /* 局部静态变量,记录所有对象调用publicMethod方法的数据 */ static int pageCount = 0; pageCount ++; } #pragma mark - #pragma mark Private Method - (void)privateMethod { } @end