一. @synthesize的错误使用方式

类1和类2是继承关系, name是类1的属性

但是类2的实现里加入了@synthesize name = _name;

导致类1的setName name 方法都被重写了

调用结果: 没有打印任何语句

类1:

#import <Foundation/Foundation.h>

@interface MyTestObj : NSObject
@property (nonatomic, strong) NSString *name;

@end
#import "MyTestObj.h"

@implementation MyTestObj
@synthesize name = _name;
- (void)setName:(NSString *)name
{
    _name = name;
    NSLog(@"%s invoke", __func__);
}
@end

类2:

#import "MyTestObj.h"

@interface MyCartObj : MyTestObj

@end
#import "MyCartObj.h"

@implementation MyCartObj
@synthesize name = _name;


@end

 

MyCartObj *cart = [[MyCartObj alloc] init];
    [cart setName:@"myname"];

调用结果: 没有打印任何语句

原因: 因为类2使用了@synthesize name = _name, 所以 类1的setName name 方法都被重写了;

相关文章:

  • 2021-11-08
  • 2021-12-07
  • 2021-11-26
  • 2022-12-23
  • 2022-12-23
  • 2021-12-03
  • 2021-05-23
猜你喜欢
  • 2022-01-18
  • 2022-12-23
  • 2022-12-23
  • 2021-05-08
  • 2021-05-31
  • 2022-12-23
  • 2021-11-08
相关资源
相似解决方案