我的代碼中有這樣的東西,多年來運行良好
NSMutableArray* DeviceList = [NSMutableArray alloc] init]; // Multi-dimensional (n x m) mutable Array filled throughout the code before arriving here:
if ([[DeviceList objectAtIndex:i] count] == 9))
{
[DeviceList removeObjectAtIndex:i];
}
我有一段時間沒有接觸該專案,現在升級到 Xcode 13 并收到以下錯誤:
發現多個名為“count”的方法具有不匹配的結果、引數型別或屬性
左側窗格中的錯誤串列顯示了 12 個已宣告計數的選項。
那么是什么改變了簡單的
someNSUInteger = [[someArray] count];
創建一個錯誤,什么是在 100 多個實體中修復它而不用 (NSMutableArray*) 強制轉換每個實體的好方法?
非常感謝!
uj5u.com熱心網友回復:
objectAtIndex 回傳“id”(任何型別的物件)。在它曾經是許可的之前,您可以呼叫任何方法(例如“count”)。
撰寫此代碼的更好方法是宣告一個中間變數:
NSArray *deviceRow = [DeviceList objectAtIndex:i];
if ([deviceRow count] == 9) {
或者如果您知道陣列中的專案的型別,假設您有字串:
NSArray<NSString *> *deviceRow = [DeviceList objectAtIndex:i];
if ([deviceRow count] == 9) {
甚至更好:
NSArray<NSString *> *deviceRow = DeviceList[i];
if (deviceRow.count == 9) {
另一個問題是這樣的例子太多了,你寧愿不要到處碰它。
修復 100 次出現中的大多數的一種方法是為 DeviceList 定義一個包裝類,而不是使用“裸”NSMutableArray:
@interface MyDeviceList
- (nonnull instancetype)init;
- (nullable NSArray *)objectAtIndex:(NSUInteger)index;
... any other NSMutableArray methods used in the code ...
@end
并將陣列實體化替換為:
MyDeviceList *DeviceList = [MyDeviceList new];
希望您的實體化比不安全的用法少得多。
如果碰巧您非常需要它,您還可以在 MyDeviceList 中使用一些輔助方法,例如“countAtIndex”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/426854.html
