1.下載protobuf
使用git的方式到開源社區(qū)下載protobuf,在終端種輸入以下命令:
git clone https://github.com/google/protobuf.git
2.安裝brew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
3.使用brew安裝protoc
brew install protobuf
4.安裝 automake
brew install automake
brew install libtool
5.將ProtoBuf協(xié)議文件編譯為OC文件
protoc --proto_path=. --objc_out=. UpDriverPosition.proto
protoc --proto_path=路徑1--objc_out=路徑2 XXXX.proto
路徑1 : 創(chuàng)建的proto文件所在目錄
路徑2 : 轉(zhuǎn)換后的文件輸出路徑
XXXX.proto : 創(chuàng)建的proto文件名稱
例:
在桌面創(chuàng)建放proto文件的文件夾 "MySrc", 在 "MySrc" 里創(chuàng)建proto文件auth.proto, 在桌面創(chuàng)建放轉(zhuǎn)換后的文件的文件夾 "MyGen", 則在終端
先cd 到桌面
protoc --proto_path=MySrc --objc_out=MyGen MySrc/auth.proto
執(zhí)行命令后會(huì)發(fā)現(xiàn)在 "MyGen" 文件夾中出現(xiàn) Auth.pbobjc.h / Auth.pbobjc.m, 這兩個(gè)就是我們項(xiàng)目中需要的文件踢故。
6.將生成的文件拖到工程中
1) 倒入頭文件 設(shè)置接受model(link)
#import <Foundation/Foundation.h>
#import "LinkMessage.pbobjc.h"
@interface ForwardLinkMessageApi : NSObject
@property(nonatomic,strong)linkMessage*link;
@end
7. 實(shí)現(xiàn)方法
#pragma mark - Private Methods 序列化
- (nullable NSData *)encode:(linkMessage *)link {
return [link data];
}
// 反序列化
- (linkMessage *)decode: (nonnull NSData *)data {
return [linkMessage parseFromData:data error:nil];
}
#pragma mark - Lazy Methods
-(linkMessage*)link{
if (_link == nil) {
_link = [linkMessage new];
_link.link = @"1111111";
_link.iconLink = @"1111111";
_link.title = @"111111";
_link.dec =@"1111111";
}
return _link;
}
8. 使用
NSData *reader = [self encode:self.link];
NSLog(@"%@", reader);
linkMessage *linkObj = [self decode:reader];
NSLog(@"%@", linkObj);