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

iOS UITableViewCell 按鈕點擊獲取 IndexPath:NSLog 格式字符串錯誤導致輸出異常

     編輯:程式設計綜合問答

Cell 中按鈕點擊事件打印 indexPath 時,NSLog(@\"@%\", indexPath) 格式字符串錯誤(@% 應為 %@),導致輸出異常。

錯誤代碼

- (IBAction)addItemIntoOrder:(id)sender {
    NSLog(@"@%", indexPath);      // ❌ 格式錯誤
    NSLog(@"@%", indexPath.row);  // ❌
}

修正代碼

- (IBAction)addItemIntoOrder:(id)sender {
    NSLog(@"%@", indexPath);       // ✅ %@ 輸出對象描述
    NSLog(@"%ld", (long)indexPath.row); // ✅ %ld 輸出長整型
}

NSLog 格式佔位符速查

佔位符類型示例
%@對象NSLog(@\"%@\", obj)
%d/%iintNSLog(@\"%d\", 42)
%ldlong / NSIntegerNSLog(@\"%ld\", (long)idx)
%ffloat/doubleNSLog(@\"%f\", 3.14)
%p指針地址NSLog(@\"%p\", ptr)

傳遞 IndexPath 到 Cell 的正確方式

- (UITableViewCell *)tableView:... cellForRowAtIndexPath:... {
    Cell *cell = ...;
    cell.indexPath = indexPath; // 屬性傳遞
    return cell;
}

// Cell.m
- (IBAction)btnTapped:(id)sender {
    NSLog(@"Row: %ld", (long)self.indexPath.row);
}

格式字符串正確,調試輸出才可信。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved