获取tableview行的索引路径

时间:2014-12-01 19:10:09

标签: ios objective-c uitableview

我在tableView中的单元格中有M13Checkbox。当用户选中此复选框时,我想在核心数据中保存一些数据

- (IBAction)completed:(M13Checkbox *)sender {


    NSDate *now = [NSDate date];
    NSNumber *yes = [NSNumber numberWithBool:YES];

    NSManagedObjectContext *context = [self managedObjectContext];

    NSManagedObject *selectedHabit = [self.habits objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
    self.habit = selectedHabit;

    NSNumber *habitID = [self.habit valueForKey:@"habitID"];

    NSNumber *habitRepeats = [self.habit valueForKey:@"habitRepeats"];

    //getting number of habit reoeats for Smart habits function
    int i = [habitRepeats intValue] + 1;
    NSNumber *repeats = [NSNumber numberWithInt:i];
    [self.habit setValue:repeats forKey:@"habitRepeats"];

    //saving completion to core data
    NSManagedObject *habitForDate = [NSEntityDescription insertNewObjectForEntityForName:@"HabitForDate" inManagedObjectContext:context];
    [habitForDate setValue:now forKey:@"date"];
    [habitForDate setValue:habitID forKey:@"habitID"];
    [habitForDate setValue:yes forKey:@"completed"];

    [context deleteObject:habitForDate];

     NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }

桌面视图中的习惯有不同的关键词" habitID",habitForDate总是复习" 1"作为" habitID"的价值我认为问题出在代码的下面部分,我的索引错误

 NSManagedObject *selectedHabit = [self.habits objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
    self.habit = selectedHabit;

我的问题是,如何获取复选框被cliked的单元格的indexPath

2 个答案:

答案 0 :(得分:0)

- (IBAction)completed:(M13Checkbox *)sender {
    UITableViewCell * cell = [[sender superView] superView]; // if you added it to cell's content view.
    NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];

    ....
}

答案 1 :(得分:-1)

我这样做的一种方法是使用类别UIView + Data.h并附加额外的数据。

#import "UIView+Data.h"
#import <objc/runtime.h>

const char * const viewUserDataKey = "view.userData";
@implementation UIView (Data)
- (id)userData {
    return objc_getAssociatedObject(self, viewUserDataKey);
}

- (void)setUserData:(id)userData {
    objc_setAssociatedObject(self, viewUserDataKey, userData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end

此外,在头文件中有一个属性@property (nonatomic, strong) id userData;

您可以在您的课程中导入以上类别,并将indexPath附加到单元格内的复选框checkBox.userData = indexPath我不确定它是否完美,但我的应用程序已在App Store中运行且工作正常!

并且,在您的方法中,您可以将indexPath读回

- (IBAction)completed:(M13Checkbox *)sender {
   NSIndexPath *indexPath = (NSIndexPath*)sender.userData;
}