自學iOS開發系列----OC(類別和擴展)

類別(Category)
1.類別的作用:爲已知的類型增加新的方法

2.類別的侷限性
①不能添加實例變量;
②方法名衝突,類別中方法的優先級會更高

3.類別的應用場景:將類的實現分散到不同的文件或框架中

4.創建Category文件
①command+N
②Objective-C File
Objective-C File
③添加類型和類別名稱
File: Printf
File Type: Category
Class: NSString
Printf

5.新建類別,在一個字符串後面追加一個字符串,返回一個新的字符串
新建NSString+Print類別

①NSString+Print.h

#import <Foundation/Foundation.h>

@interface NSString (Printf)

- (NSString *)appendStringByStrLast:(NSString *)strLast;

@end

②NSString+Printf.m

#import "NSString+Printf.h"

@implementation NSString (Printf)

- (NSString *)appendStringByStrLast:(NSString *)strLast {
    //字符串追加
    NSString * ret = [NSString stringWithFormat:@"%@%@",self,strLast];
    return ret;
}

@end

③main.m

#import <Foundation/Foundation.h>
#import "NSString+Printf.h"

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

        NSString * str = @"春風十里,";
        NSString * strNew = [str appendStringByStrLast:@"不如你"];
        NSLog(@"%@",strNew);
    }
    return 0;
}

擴展(Extension)

1.擴展和類別的區別:擴展既可以爲類型增加實例變量,也可以增加方法

2.擴展的作用:將擴展的內容(實例變量,方法)變爲私有

3.創建Extension文件
①command+N
②Objective-C File
Objective-C File
③添加類型和擴展名
File: PrivateMethod
File Type: Extension
Class: Student
PrivateMethod

4.創建一個學生類,爲學生類添加擴展類
新建Student類
①Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject

- (void)sayStudentName;

@end

②Student_PrivateMethod.h

#import "Student.h"

@interface Student () {
    int _age;
}

- (void)studentName;

@end

③Student.m

#import "Student.h"
#import "Student_PrivateMethod.h"

@implementation Student

- (void)sayStudentName {
    //擴張變量和方法只能在自己的.m裏調用
    [self studentName];
}

- (void)studentName {
    _age = 28;
    NSLog(@"我叫趙麗穎");
}

@end

④main.m

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

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Student * student = [[Student alloc] init];
        [student sayStudentName];
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章