gpt4 book ai didi

Objective-C ARC 属性重新声明混淆

转载 作者:搜寻专家 更新时间:2023-10-30 19:44:24 25 4
gpt4 key购买 nike

我有以下代码:

// MyObject.h
#import <Foundation/Foundation.h>

@interface MyObject : NSObject
@property (nonatomic, readonly) id property;
@end

// MyObject.m
#import "MyObject.h"

@interface MyObject ()
@property (nonatomic, copy, readwrite) id property;
@end

@implementation MyObject
@synthesize property = _property;
@end

这会生成以下编译器警告和错误:

warning: property attribute in continuation class does not match the primary class
@property (nonatomic, copy, readwrite) id property;
^
note: property declared here
@property (nonatomic, readonly) id property;
^
error: ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

但是,如果我将类延续的属性重新声明更改为具有 weak 的存储限定符,则不会生成任何警告或错误。然而,(令人担忧的是?)为 -[MyObject setProperty:] 生成的代码调用了 objc_storeStrong 而不是我预期的 objc_storeWeak

据我所知,从 LLVM 3.1 开始,合成 ivars 的默认存储是 strong。我想我的问题是:为什么 codegen 更喜欢 header 中的声明而不是我在实现中的重新声明?其次,为什么当我重新声明为 copy 而不是 weakassign 时它会提示?

最佳答案

我明白你的问题了...

  • 您想在 MyObject 类成员方法中读写 myproperty。
  • 但是,想只读其他类的 myproperty。

//MyObject.h

@interface MyObject : NSObject
{
@private
id _myproperty;
}
@property (nonatomic, copy, readonly) id myproperty;
@end

//MyObject.m

#import "MyObject.h"

@interface MyObject ()
// @property (nonatomic, copy, readwrite) id myproperty; // No needs
@end

@implementation MyObject
@synthesize myproperty = _myproperty;


- (void)aMethod
{
_myproperty = [NSString new]; // You can read & write in this class.
}

@end

//Ohter.m

#import "MyObject.h"

void main()
{
MyObject *o = [MyObject new];
o.myproperty = [NSString new]; // Error!! Can't write.
o._myproperty = [NSString new]; // Error!! Can't acsess by objective c rule.
NSString *tmp = o.myproperty; // Success readonly. (but myproperty value is nil).
}

关于Objective-C ARC 属性重新声明混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11787615/

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