gpt4 book ai didi

ios - 使用 ARC 时无法从一个类调用方法到另一个类

转载 作者:行者123 更新时间:2023-11-28 20:13:39 25 4
gpt4 key购买 nike

我知道如何调用一个类的方法给另一个类。然而,这一次它对我不起作用,它只会让我发疯。下面是我的代码

MenuPageCell.h

#import <UIKit/UIKit.h>
@class MenuPageViewController;
@interface MenuPageCell : UITableViewCell{
NSInteger m_cellIndex;
MenuPageViewController *m_parentViewController;
}
@property(nonatomic, assign) NSInteger m_cellIndex;
@property(nonatomic, strong) MenuPageViewController *m_parentViewController;
-(IBAction) addToCart;

@end

MenuPAgeCell.m

#import "MenuPageCell.h"
#import "MenuPageViewController.h"
@implementation MenuPageCell

@synthesize m_cellIndex;
@synthesize m_parentViewController;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
-(IBAction) addToCart
{
NSLog(@"Add To cart = %d",self.m_cellIndex);

[m_parentViewController addItemToCart:self.m_cellIndex];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];

// Configure the view for the selected state
}

MenuPageViewController.m

-(void) addItemToCart:(NSInteger)aIndexItem
{
NSLog(@"In Add to Cart method");
}

现在,此代码适用于非 ARC Used 项目,但不适用于我。我知道这应该是个愚蠢的错误,但我无法弄明白。

感谢和问候

马约尔

最佳答案

从单元格引用 ViewController 是一个设计缺陷,请考虑改用委托(delegate)。但是,如果您真的需要 ViewController 属性,请将其设置为 weak 而不是 strong 因为目前您最终会遇到保留循环。

@protocol MenuPageCellDelegate<NSObject>
- (void)addItemToCart:(NSInteger)aIndexItem;
@end

@interface MenuPageCell : UITableViewCell {
NSInteger m_cellIndex;
}

@property(nonatomic, assign) NSInteger m_cellIndex;
@property(nonatomic, weak) id<MenuPageCellDelegate> delegate;

-(IBAction) addToCart;

@end

@implementation MenuPageCell
...
-(IBAction) addToCart
{
NSLog(@"Add To cart = %d",self.m_cellIndex);

if ([self.delegate responsToSelector:@selector(addItemToCart:)]) {
[self.delegate addItemToCart:self.m_cellIndex];
}
}
...
@end

MenuPageCellDelegate 添加到 MenuPageViewController 的实现协议(protocol)列表中,并且(如果它正在实现 UITableViewDataSource 协议(protocol))在 tableView:cellForRowAtIndexPath 中: 方法编写 cell.delegate = self; 而不是 cell.m_parentViewController = self;

关于ios - 使用 ARC 时无法从一个类调用方法到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19047164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com