Objective-C: How to generate one unique NSInteger

2019-09-16 03:02发布

Possible Duplicate:
Pass two integers as one integer

Will this work in Objective-C? Pass two integers as one integer

If so, how do I do it with NSInteger?

I'm asking because I want to calculate a unique NSInteger tag from the NSUIntegers row & section of a UITableView?

See, I'm dealing with a UITableViewController that has three sections, which each have multiple rows. Every row has a UISwitch, and each UISwitch is linked to the same target-action method, switchAction:.

In switchAction:, my plan is to inspect the sender's tag to figure out the UISwitch's NSIndexPath (section & row) of the UITableView.

So, I want two methods like:

+ (NSInteger)integerFromInteger1:(NSInteger)int1 integer2:(NSInteger)int2;
+ (NSIndexPath *)indexPathFromInteger:(NSInteger)integer;

The first method may work better written in C. That works too if you prefer.

3条回答
别忘想泡老子
2楼-- · 2019-09-16 03:45

Rather than messing around with bit-shifting, try this:

First, find the UITableViewCell containing the UISwitch. If you have a custom UITableViewCell subclass, just direct the UISwitch's target/action to a method on the cell that contains it. If you are using a stock UITableViewCell, you could find the UITableViewCell containing the UISwitch by calling superview in a loop.

Once you have the UITableViewCell, call a method on your view controller (or whatever has access to the UITableView) and you can call UITableView's indexPathForCell: method to get an NSIndexPath object with the section and row.

查看更多
相关推荐>>
3楼-- · 2019-09-16 03:47

According to How to convert An NSInteger to an int?, NSInteger will always be at least 32 bits on every system/architecture, so yes, the answers to Pass two integers as one integer will work.

查看更多
仙女界的扛把子
4楼-- · 2019-09-16 03:50

Based on @benzado's answer, I came up with a beautiful solution for how to get the index path of the UISwitch that sent the switchAction: message.

- (void)switchAction:(id)sender {
    UISwitch *onOff = (UISwitch *)sender;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:
                              (UITableViewCell *)[onOff superview]];
    // carry on...
}

No tags necessary. Just keep your pants on.

查看更多
登录 后发表回答