iOS笔记—extension

extension像没有命名的category。因此被称为:匿名类别,也叫类扩展

//
//  Person.h
//  匿名类别
//
//  Created by hhg on 15-6-15.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject {
@private NSUInteger _number;
}

- (void)eat;
- (void)song;
@end
//
//  Person.m
//  匿名类别
//
//  Created by hhg on 15-6-15.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import "Person.h"

@interface Person () {
    NSString *_name; 
}

- (void)jump;

@end



@implementation Person {
    NSUInteger _age; // 私有的成员变量, 相当于在匿名类别里声明变量;
}

- (void)eat {
    NSLog(@"吃饭.....");
}


- (void)song {
    NSLog(@"唱歌.....");
}

/// 本类使用
- (void)jump {
    _age = 3;
    NSLog(@"jump ,%lu times ",(unsigned long)_age);
}

@end

正常调用的时候extension只能在自己内部调用,外部调用则报错

//
//  main.m
//  匿名类别
//
//  Created by hhg on 15-6-15.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        Person *p = [[Person alloc] init];

        [p eat];
        [p song];
        // [p test]; // 外部直接调用则报错

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/csdn_hhg/article/details/80490548