簡體   English   中英

NSMutableArray的count方法導致錯誤的訪問錯誤?

[英]NSMutableArray's count method causes a bad access error?

我看到一些類似的問題,但沒有簡單的答案。 在我真正使用它們之前,我只是在玩NSMutableArray來感受它們。 出於某種原因,當我嘗試在數組上調用count時,它給了我一個EXC_BAD_ACCESS錯誤,我無法找出原因。

    - (void) applicationDidFinishLaunching:(UIApplication*)application 
{   
    // Create window and make key
    _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [_window makeKeyAndVisible];

    NSMutableArray* test = [[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:@"first!"], [NSString stringWithFormat:@"second!"], nil];
    [test insertObject:[NSString stringWithFormat:@"inserted"] atIndex:0];
    NSLog(@"%@", [test objectAtIndex:0]);
    NSLog(@"%@", [test objectAtIndex:1]);
    NSLog(@"%@", [test objectAtIndex:2]);
    NSLog(@"%@", [test count]); //bad access here
}

所有插入和訪問除了計數方法工作都很好。 我不明白為什么這不起作用,非常感謝一些幫助。 謝謝!

%@格式說明符打印對象。 -count的返回值只是一個無符號整數。 您應該為該類型使用格式說明符%u

問題是[test count]返回NSUInteger而不是指針(指向NSObject )。 試試這個:

NSLog(@"%u", [test count]);

請注意,使用%d也可以,但%u是首選。

- (NSUInteger)count; 返回NSUInteger

請改用:

NSLog(@"%u", [test count]); //bad access here

count工作得很好。 但它返回一個NSUInteger原語,而不是一個指向NSObject子類的指針。 %@ string格式化程序期望指向一個對象並記錄從該對象的-description方法返回的NSString 當傳遞給它一個NSUInteger NSLog假定它是一個對象的指針和忠實地試圖發送-description消息給存儲器地址3引起該EXEC_BAD_ACCESS。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM