[英]iPhone SDK: NSMutableArray count causes EXC_BAD_ACCESS
[英]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.