首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

iOS JSONModel 巢狀模型陣列屬性宣告錯誤解決:缺少 Protocol 宣告

     編輯:程式設計疑難解答

問題現象

使用 JSONModel 將網路資料映射為模型時,外層模型包含一個內層模型陣列。按照文檔在屬性宣告中使用 <InnerModel> 卻報錯,必須加上 * 才能編譯通過。

根本原因

<> 語法包裹的是 Protocol (協議),而非具體類別。必須確認內層模型 DataModel.h 中已使用 @protocol 關鍵字宣告協議,並讓該類別遵循此協議。

正確宣告範例

// DataModel.h
@protocol DataModel <JSONModel>
@property (nonatomic, strong) NSString *name;
// ... 其他屬性
@end

@interface DataModel : JSONModel <DataModel>
@end

// OuterModel.h
@protocol OuterModel <JSONModel>
@property (nonatomic, strong) NSArray<DataModel> *items; // 使用協議名
@end

關鍵點總結

  • JSONModel 陣列屬性泛型參數必須是 Protocol 名稱。
  • 內層模型類別需同時 宣告協議 並 遵循該協議。
  • 屬性宣告可用 NSArray<ProtocolName> *items 或 NSArray *items 搭配 @property (nonatomic, strong) NSArray<DataModel> *items; (需導入頭文件)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved