2017-08-09 80 views
1

零對象我有這樣的提示以下錯誤:嘗試插入從對象

- [__ NSPlaceholderArray initWithObjects:數:]:嘗試從物體[1539]

插入零對象有時會發生我試圖挖掘在屏幕上數倍,因爲代碼是很少,所以所有的代碼粘貼下面

@interface ViewController() 
@property (nonatomic,weak) NSTimer *timer; 
@property (nonatomic,strong)NSMutableArray * testArray; 
@property (nonatomic,strong) dispatch_queue_t queue1; 
@property (nonatomic,strong) dispatch_queue_t queue2; 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    self.testArray = [NSMutableArray array]; 
    _queue1 = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT); 
    _queue2 = dispatch_queue_create("test",DISPATCH_QUEUE_SERIAL); 
    NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(addObjectforArray) userInfo:nil repeats:YES]; 
    [timer fire]; 
} 

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { 
     dispatch_async(_queue2, ^{ 
      NSLog(@"touchesBeganThread:%@",[NSThread currentThread]); 
      NSArray * testTempArray = [NSArray arrayWithArray:self.testArray]; 
      for (UIView *view in testTempArray) { 
       NSLog(@"%@",view); 
      } 

    }); 
} 

- (void)addObjectforArray{ 
    dispatch_async(_queue1, ^{ 
     NSLog(@"addObjectThread:%@",[NSThread currentThread]); 
     [self.testArray addObject:[[UIView alloc]init]]; 
    }); 
} 

我不明白爲什麼會這樣,如果我改變_queue1到DISPATCH_QUEUE_SERIAL,它變得正常。

我該如何理解這個問題?如果有人能夠說出一些光芒,那將是美好的。

回答

0

你的代碼有多個問題。他們可以隨機導致各種錯誤。

  1. UIView應該在主線程中使用dispatch_get_main_queue()創建。 https://developer.apple.com/documentation/uikit

    在大多數情況下,使用UIKit類只能從應用程序的主線程或主調度隊列。此限制適用於從 UIResponder 派生的類,或涉及以任何方式操縱應用程序用戶界面的類。

  2. 屬性testArraynonatomic但在兩個線程中被訪問。該物業應該是atomic。它現在運行良好,但它很脆弱。如果將來testArray突變,該應用程序將隨機崩潰。

  3. NSArray不是線程安全的。它應該在多線程訪問時被鎖定或被其他方式保護。

  4. 正如@Nirmalsinh指出的那樣,dispatch_async是多餘的(實際上是有害的)。

我不確定您是否大量簡化了代碼或只是爲了測試某些內容。如果您沒有進行長時間的工作,則可能需要在dispatch_async中使用dispatch_get_main_queue()。它會讓你免受很多麻煩。

-1

看來你是在你的數組中插入nil值。你不能在數組或字典中添加nil。

- (void)addObjectforArray{ 
     NSLog(@"addObjectThread:%@",[NSThread currentThread]); 
     UIView *view = [[UIView alloc] init]; 
     if(view != nil) 
      [self.testArray addObject:view]; 
} 

在方法中沒有必要使用隊列。您已經在使用NSTimer。

嘗試以上檢查。它會幫助你。

+0

' - [UIView init]'永遠不會返回'nil'。 –

+0

你需要分配它。 [[UIView alloc] init] – Nirmalsinh

相關問題