ios - 为什么class对象的property属性是retain而不是copy?

标签 ios objective-c memory-management

<分区>

我试图将自定义对象传递给下一个 View Controller ,但我遇到了这个错误-[ClassName copyWithZone:] unrecognized selector sent to instance

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"attemptDetails"])
    {
        ResultsVC *vc = segue.destinationViewController;
        vc.selectedEntry = selectedEntry;
    }
}

@property (nonatomic, retain) ClassName *selectedEntry;//为什么是retain而不是copy?

我仍然很困惑属性属性以及为什么某些类型使用某些属性,比如 NSString 使用 (nonatomic, copy) 和 CLLocationCoordinate2D 使用 (nonatomic, readonly) .

有人可以向我解释或链接引用每个属性属性是如何工作的吗?非常感谢!

最佳答案

property属性的解释有很多,

引用链接,

Objective-C ARC: strong vs retain and weak vs assign

https://stackoverflow.com/a/4511004/4294543

@property and retain, assign, copy, nonatomic in Objective-C

简而言之,我的理解是,

retain :它在创建的对象上工作,它只是增加引用计数。

  • 在你的例子中,你已经有了模型类对象,所以不需要复制第二个 vc 属性,你只需要将它保留到第二个 vc 属性。

copy:您分配给属性的值也可以被复制并用于其他目的(创建对象的浅拷贝,当对象可变时需要,并且需要在完成后释放)。

nonatomic:线程访问速度更快,但您不能同时访问和更改您的属性。

readonly :您不能直接为属性分配新值。

即使我在我的项目中运行过你的案例,

#import "ViewController.h"
#import "TestViewController.h"
#import "CustomClass.h"
@interface ViewController (){

    CustomClass *classT;
}

@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    classT = [[CustomClass alloc]init];
    classT.test = YES;

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)btn:(id)sender {
    TestViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"TestViewController"];
    vc.className = classT;
    [self presentViewController:vc animated:YES completion:nil];
}
@end




#import <UIKit/UIKit.h>
#import "CustomClass.h"

@interface TestViewController : UIViewController


@property (nonatomic,retain) CustomClass *className; // Work as i said

//@property (nonatomic,copy) CustomClass *className; // Makes a copy of an object, and returns it with retain count of 1. If you copy an object, you own the copy. This applies to any method that contains the word copy where “copy” refers to the object being returned thats why here you will get crash


@end

关于ios - 为什么class对象的property属性是retain而不是copy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42342818/

上一篇:ios - NSNotFound 不适用于 NSUser 默认值

下一篇:ios - Auto Layout垂直空间计算方法

相关文章:

ios - SwiftUI AspectFill

iphone - iOS:CGContextRef drawRect 与输入不一致

ios - 如何消除偏色或调整白平衡?

objective-c - 模态呈现 View Controller - iPad

objective-c - GCC 编译器——错误或未指定的行为?

objective-c - copy/mutableCopy 操作增量保留计数值吗?? ( objective-c )

ios - iOS 10 中 touchesBegan 的奇怪延迟

ios - Xcode 8.3 自动完成和语法突出显示不起作用

java - 哪种数据结构占用更多内存?

java - 如何衡量C#和Java内存使用的差异?